<style>
  .layui-form-label {
    width: 90px;
  }

  .layui-input-block {
    margin-left: 120px;
  }

  #erpPurchaseOrder-view .layui-disabled {
    color: #393d49 !important;
    background-color: #fff;
  }

  .layui-col-space15 {
    margin: 0;
  }

  #qrcode img {
    margin: auto;
  }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-card-body">
      <!-- 头部操作栏 -->
      <div class="layui-form lay-header">
        <div class="toolbar">
          <div class="layui-form-item lay-query-content">
            <div class="lay-query-box">
              <div class="query-lt">
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">订单编号：</label>
                  <div class="layui-input-inline mr0">
                    <input
                      name="sn"
                      class="layui-input"
                      type="text"
                      placeholder="输入订单编号"
                      autocomplete="off"
                    />
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">物料名称：</label>
                  <div class="layui-input-inline mr0">
                    <input
                      name="productName"
                      class="layui-input"
                      type="text"
                      placeholder="请输入物料名称"
                      autocomplete="off"
                    />
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">供应商：</label>
                  <div class="layui-input-inline mr0">
                    <select
                      id="querySupplierId"
                      name="querySupplierId"
                      lay-search=""
                      class="common-select-search"
                    ></select>
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">状态：</label>
                  <div class="layui-input-inline mr0">
                    <select
                      id="status"
                      name="status"
                      class="common-select-search"
                    ></select>
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">部门：</label>
                  <input name="queryDepartmentId" type="hidden" />
                  <div
                    class="layui-input-inline mr0"
                    id="selectDepartmentQuery"
                  ></div>
                </div>
                <!-- <div class="layui-inline">
                                    <label class="layui-form-label w-auto">申请人：</label>
                                    <div class="layui-input-inline mr0">
                                        <select id="queryPersonnelId" name="queryPersonnelId" lay-search="">
                                        </select>
                                    </div>
                                </div> -->
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">时间段：</label>
                  <div class="layui-input-inline mr0">
                    <input
                      name="createTime"
                      id="pTime"
                      class="layui-input date-icon"
                      type="text"
                      placeholder="选择时间"
                      style="width: 200px"
                      readonly
                    />
                  </div>
                  <input name="startCreateTime" id="sTime" type="hidden" />
                  <input name="endCreateTime" id="eTime" type="hidden" />
                </div>
              </div>
              <div class="query-rt">
                <div class="layui-inline">
                  <button
                    class="layui-btn icon-btn color-green"
                    lay-filter="formSubSearchLog"
                    lay-submit
                    layui-form-keyDownSearch="true"
                  >
                    查询
                  </button>
                  <button
                    class="layui-btn icon-btn color-white"
                    lay-filter="resets"
                    lay-submit
                  >
                    重置
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="lay-btn-rows">
          <div class="lay-btn-box">
            <div class="lay-btn-lt">
              <button
                id="erpPurchaseOrder-btn-add"
                class="layui-btn icon-btn color-reseda"
              >
                添加
              </button>
              <button
                id="confirmSelectBtn"
                class="layui-btn icon-btn color-reseda"
                style="display: none"
              >
                确认选择
              </button>
            </div>
            <div class="lay-btn-rt"></div>
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <table
        class="layui-table"
        id="erpPurchaseOrder-table"
        lay-filter="erpPurchaseOrder-table"
      ></table>
    </div>
  </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="erpPurchaseOrder-table-bar">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="view">详情</a>
  <!-- {{# if(d.status != 'closed'){ }} -->
  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
  <!-- {{# } }}-->
  <!-- {{# if(d.status == 'stayAudit'){ }}  -->
  <a class="layui-btn layui-btn-xs" lay-event="audit">审核</a>
  <!-- {{# } }}-->

  <a class="layui-btn layui-btn-xs" lay-event="print">打印</a>

  <!-- {{# if(d.status != 'success'){ }} {{# if(d.status != 'closed'){ }} -->
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
  <!-- {{# } }} {{# } }} {{# if(d.status == 'stayAudit'){ }} -->
  <!-- {{# } }} {{# if(d.status == 'success'){ }} -->
  <!--<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="logistics">物流</a>-->
  <!-- {{# if(!d.isGenerateOrder && (d.shippingStatus == 0 || d.shippingStatus == 1) && d.isCanStorage == 1){ }} -->
  <!--<a class="layui-btn layui-btn layui-btn-xs" lay-event="generate">生成入库单</a>-->
  <!-- {{# } }} -->
  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="close">关闭</a>
  <!-- {{# } }} -->
</script>

<!-- erpPurchaseOrder表单弹窗 -->
<script type="text/html" id="erpPurchaseOrder-form">
  <form lay-filter="erpPurchaseOrder-form" class="layui-form form-scroll">
    <div class="open-details-box pd-20">
      <div class="layui-row" style="padding-top: 20px;">
        <div class="layui-col-xs3">
          <label class="layui-form-label"
            >采购类型<span style="color:red;">*</span></label
          >
          <div class="layui-input-block">
            <select
              id="purchaseType"
              name="purchaseType"
              lay-filter="purchaseType"
              lay-verify="required"
              required
            ></select>
          </div>
        </div>
        <div class="layui-col-xs3">
          <label class="layui-form-label"
            >紧急程度<span style="color:red;">*</span></label
          >
          <div class="layui-input-block">
            <select
              id="emergencyDegree"
              name="emergencyDegree"
              lay-verify="required"
              required
            ></select>
          </div>
        </div>
        <div class="layui-col-xs3">
          <label class="layui-form-label"
            >供应商<span style="color:red;">*</span></label
          >
          <div class="layui-input-block">
            <select
              id="supplierId"
              name="supplierId"
              lay-filter="supplierId"
              class="common-select-search"
              lay-search=""
            ></select>
          </div>
        </div>
        <div class="layui-col-xs3">
          <label class="layui-form-label"
            >供应商联系人<span style="color:red;">*</span></label
          >
          <div class="layui-input-block">
            <select
              id="businessContact"
              name="businessContact"
              lay-verify="required"
              required
              lay-search=""
            ></select>
          </div>
        </div>
        <div class="layui-col-xs3" style="margin-top: 10px;">
          <label class="layui-form-label">审核部门</label>
          <div class="layui-input-block">
            <input
              name="departmentName"
              id="departmentName"
              class="layui-input"
              disabled
            />
          </div>
          <input
            name="departmentId"
            id="departmentId"
            class="layui-input"
            type="hidden"
          />
          <!--<div class="layui-input-block" id="selectDepartment" disabled="true"></div>-->
        </div>
        <div class="layui-col-xs3" style="margin-top: 10px;">
          <label class="layui-form-label">审核岗位</label>
          <div class="layui-input-block">
            <input name="postId" id="postId" class="layui-input" disabled />
          </div>
        </div>
        <div class="layui-col-xs3" style="margin-top: 10px;">
          <label class="layui-form-label">是否已签约</label>
          <div class="layui-input-block">
            <select name="hasSign" lay-filter="hasSign">
              <option value="">请选择是否签约</option>
              <option value="1">已签约</option>
              <option value="0">未签约</option>
            </select>
          </div>
        </div>
        <div
          class="layui-col-xs3"
          style="margin-top: 10px;"
          id="contractIdSelect"
        >
          <label class="layui-form-label">选择合同</label>
          <div class="layui-input-block">
            <select
              name="contractId"
              id="contractId"
              lay-filter="contractId"
            ></select>
          </div>
        </div>

        <!--                <div class="layui-col-xs3" style="margin-top: 10px;">-->
        <!--                    <label class="layui-form-label">订单审核人<span style="color:red;">*</span></label>-->
        <!--                    <div class="layui-input-block">-->
        <!--                        <select id="auditor" name="auditor" lay-verify="required" required lay-search=""></select>-->
        <!--                    </div>-->
        <!--                </div>-->
      </div>
      <table
        class="layui-table"
        id="erpPurchaseOrder-add-table"
        lay-filter="erpPurchaseOrder-add-table"
      ></table>
    </div>
    <div class="layui-form-item text-right pd-20">
      <button
        class="layui-btn layui-btn-primary"
        ew-event="closeDialog"
        type="button"
      >
        取消
      </button>
      <button
        class="layui-btn"
        lay-filter="erpPurchaseOrder-form-submit"
        lay-submit
      >
        保存
      </button>
    </div>
  </form>
</script>

<!-- erpPurchaseOrder表单编辑弹窗 -->
<script type="text/html" id="erpPurchaseOrder-edit">
  <form lay-filter="erpPurchaseOrder-edit" class="layui-form form-scroll">
    <div class="open-details-box pd-20">
      <input name="id" type="hidden" />
      <div class="layui-row" style="padding-top: 20px;">
        <div class="layui-col-xs4">
          <label class="layui-form-label"
            >供应商<span style="color:red;">*</span></label
          >
          <div class="layui-input-block">
            <select
              id="supplierId"
              name="supplierId"
              lay-verify="required"
              required
              lay-search=""
            ></select>
          </div>
        </div>
        <div class="layui-col-xs4">
          <label class="layui-form-label">部门</label>
          <input name="departmentId" type="hidden" />
          <div class="layui-input-block" id="selectDepartmentEdit"></div>
        </div>
        <div class="layui-col-xs4">
          <label class="layui-form-label">申请人</label>
          <div class="layui-input-block">
            <select id="personnelId" name="personnelId" lay-search=""></select>
          </div>
        </div>
      </div>

      <table
        class="layui-table"
        id="erpPurchaseOrder-add-table"
        lay-filter="erpPurchaseOrder-add-table"
      ></table>

      <div id="audit" style="display: none;">
        <div class="layui-form-item">
          <label class="layui-form-label">审核</label>
          <div class="layui-input-block">
            <input
              name="status"
              type="radio"
              title="通过"
              value="success"
              lay-filter="getStatus"
              class="layui-input"
            />
            <input
              name="status"
              type="radio"
              title="驳回"
              value="fail"
              lay-filter="getStatus"
              class="layui-input"
            />
          </div>
        </div>
        <div class="layui-form-item" id="reason" style="display: none;">
          <label class="layui-form-label">驳回原因</label>
          <div class="layui-input-block">
            <textarea
              name="reason"
              placeholder="请输入驳回原因"
              type="text"
              maxlength="200"
              class="layui-textarea"
              style="width: 80%"
            ></textarea>
          </div>
        </div>
      </div>

      <div class="layui-form-item" id="viewAudit" style="display: none;">
        <label class="layui-form-label">驳回原因</label>
        <div class="layui-input-block">
          <textarea
            placeholder="请输入驳回原因"
            type="text"
            maxlength="200"
            class="layui-textarea"
          ></textarea>
        </div>
      </div>
    </div>
    <div class="layui-form-item text-right pd-20">
      <button
        class="layui-btn layui-btn-primary"
        ew-event="closeDialog"
        type="button"
      >
        取消
      </button>
      <button
        class="layui-btn"
        lay-filter="erpPurchaseOrder-edit-submit"
        lay-submit
      >
        保存
      </button>
    </div>
  </form>
</script>

<!-- erpPurchaseOrder表单弹窗 -->
<script type="text/html" id="erpPurchaseOrder-view">
  <form lay-filter="erpPurchaseOrder-view" class="layui-form model-form">
    <input name="id" type="hidden" />
    <div class="layui-form-item">
      <div class="layui-col-xs4">
        <label class="layui-form-label"
          >供应商<span style="color:red;">*</span></label
        >
        <div class="layui-input-block">
          <select
            id="supplierId"
            name="supplierId"
            lay-verify="required"
            required
            disabled
          ></select>
        </div>
      </div>
      <div class="layui-col-xs4">
        <label class="layui-form-label">部门</label>
        <input name="departmentId" lay-filter="departmentId" type="hidden" />
        <div class="layui-input-block" id="selectDepartmentView"></div>
      </div>
      <div class="layui-col-xs4">
        <label class="layui-form-label">申请人</label>
        <div class="layui-input-block">
          <select
            id="personnelId"
            name="personnelId"
            lay-verify="required"
            required
            disabled
          >
            <option>请选择申请人</option>
          </select>
        </div>
      </div>
    </div>

    <div style="margin-left: 30px;">
      <table
        class="layui-table"
        id="erpPurchaseOrder-add-table"
        lay-filter="erpPurchaseOrder-add-table"
      ></table>
    </div>
  </form>
</script>

<script type="text/html" id="erpInventoryList">
  <div class="layui-card">
    <div class="layui-card-body" style="padding-top: 20px;">
      <div class="layui-form toolbar">
        <div class="layui-form-item">
          <div class="layui-inline">
            <div class="layui-input-inline mr0">
              <input
                id="erpInventoryList-code"
                class="layui-input search-input"
                type="text"
                placeholder="输入物料编号"
              />
            </div>
          </div>
          <div class="layui-inline">
            <div class="layui-input-inline mr0">
              <input
                id="erpInventoryList-name"
                class="layui-input search-input"
                type="text"
                placeholder="输入物料名称"
              />
            </div>
          </div>
          <div class="layui-inline">
            <div class="layui-input-inline mr0">
              <input
                id="erpInventoryList-spec"
                class="layui-input search-input"
                type="text"
                placeholder="输入规格型号"
              />
            </div>
          </div>
          <div class="layui-inline">
            <div class="layui-input-inline mr0">
              <select id="erpInventoryList-way">
                <option value="">请选择计价方式</option>
                <option value="piece">按件</option>
                <option value="weight">按重量</option>
              </select>
            </div>
          </div>
          <div class="layui-inline">
            <div class="layui-input-inline">
              <input
                name="addSelfCollectedGoodsProductCategoryId"
                type="hidden"
                lay-verify="required"
              />
              <div
                class="layui-input-inline mr0"
                id="addSelfCollectedGoodsProductCategoryId"
              ></div>
            </div>
          </div>
          <div class="layui-inline">
            <button id="erpInventoryList-btn-search" class="layui-btn icon-btn">
              <i class="layui-icon">&#xe615;</i>搜索
            </button>
            <button
              id="erpInventoryList-btn-choose"
              class="layui-btn layui-btn-normal"
            >
              确认选择
            </button>
            <button
              id="erpInventoryList-btn-add"
              class="layui-btn layui-btn-normal"
            >
              添加物料
            </button>
          </div>
        </div>
      </div>
      <table
        class="layui-table"
        id="erpInventoryList-table"
        lay-filter="erpInventoryList-table"
      ></table>
    </div>
  </div>
</script>

<script type="text/html" id="erpInventoryListErpInventoryClassId">
  <option value="">请选择物料类别</option>
  <!-- {{# layui.each(d, function(index, item){ }} {{# var space = ""; if(item.grade > 0){ for(var j = 0; j < item.grade; j++){ space += "&nbsp;&nbsp;"; } } var disabled = "";
  if(item.isDisable == 1 || item.isParent){ disabled = "disabled"; } }} -->
  <option value="{{item.id}}" {{disabled}}>
    {{space}}{{item.code}}-{{item.name}}
  </option>
  <!-- {{# }) }} -->
</script>

<script type="text/html" id="quantity">
  <!-- {{# var quantity = ""; var isRequired = false; if(d.quantity != null){ quantity = d.quantity; isRequired = true; } }} -->
  <div>
    <input
      name="quantity"
      placeholder="请输入数量"
      type="text"
      value="{{quantity}}"
      lay-verify="{{isRequired ? 'required|quantity' : ''}}"
      required="{{isRequired ? true : false}}"
      class="layui-input"
      maxlength="10"
      style="border: 0;height: 28px;text-align:center;"
    />
  </div>
</script>

<script type="text/html" id="rate">
  <!-- {{# var rate = ""; var isRequired = false; if(d.rate != null){ rate = d.rate; isRequired = true; } }} -->
  <div>
    <input
      name="rate"
      placeholder="请输入税率"
      type="text"
      value="{{rate}}"
      lay-verify="{{isRequired ? 'required|rate' : ''}}"
      required="{{isRequired ? true : false}}"
      class="layui-input"
      maxlength="10"
      style="border: 0;height: 28px;text-align:center;"
    />
  </div>
</script>

<script type="text/html" id="taxPrice">
  <!-- {{# var taxPrice = ""; var isRequired = false; if(d.taxPrice != null){ taxPrice = d.taxPrice; isRequired = true; } }} -->
  <div>
    <input
      name="taxPrice"
      placeholder="请输入含税单价"
      type="text"
      value="{{taxPrice}}"
      lay-verify="{{isRequired ? 'required|rate' : ''}}"
      required="{{isRequired ? true : false}}"
      class="layui-input"
      maxlength="10"
      style="border: 0;height: 28px;text-align:center;"
    />
  </div>
</script>

<!-- 表格操作列 -->
<script type="text/html" id="erpPurchaseOrder-add-table-bar">
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script type="text/html" id="logisticsList">
  <div class="layui-card">
    <div class="layui-card-body">
      <div class="layui-form toolbar">
        <div class="layui-form-item">
          <div class="layui-inline">
            <div class="layui-input-inline mr0">
              <input
                id="erpLogistics1-transportOrderNo"
                class="layui-input"
                type="text"
                placeholder="输入物流单号"
              />
            </div>
          </div>
          <div class="layui-inline">
            <div class="layui-input-inline mr0">
              <select id="erpLogistics1-supplierId"></select>
            </div>
          </div>
          <div class="layui-inline">
            <div class="layui-input-inline mr0">
              <select id="erpLogistics1-status">
                <option value="">请选择状态</option>
                <option value="0">发货中</option>
                <option value="1">运输中</option>
                <option value="2">已签收</option>
              </select>
            </div>
          </div>
          <div class="layui-inline">
            <button id="erpLogistics1-btn-search" class="layui-btn icon-btn">
              <i class="layui-icon">&#xe615;</i>搜索
            </button>
          </div>
        </div>
      </div>
      <table
        class="layui-table"
        id="erpLogistics1-table"
        lay-filter="erpLogistics1-table"
      ></table>
    </div>
  </div>
</script>

<!-- 表格操作列 -->
<script type="text/html" id="erpLogistics1-table-bar">
  <!-- {{# if(d.isWeigh == 2){ }} -->
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="view1">详情</a>
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="info"
    >物流信息</a
  >
  <!-- {{# }else{ }} {{# if(!d.isComplete){ }} -->
  <!--<a class="layui-btn layui-btn-xs" lay-event="complete">完成车辆计划</a>-->
  <!-- {{# } }} -->
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="view">详情</a>
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="progress"
    >物流进度</a
  >
  <!-- {{# } }} -->
</script>

<script type="text/html" id="logistics-view">
  <div class="layui-row layui-col-space15">
    <div class="layui-col-md12">
      <div class="layui-card">
        <div class="layui-card-header">二维码</div>
        <div class="layui-card-body layui-form-item">
          <div id="qrcode"></div>
        </div>
      </div>
    </div>
    <div class="layui-col-md12">
      <div class="layui-card">
        <div class="layui-card-header">供应商信息</div>
        <div class="layui-card-body layui-form-item" id="supplierInfo"></div>
      </div>
    </div>
    <div class="layui-col-md12">
      <div class="layui-card">
        <div class="layui-card-header">车辆与司机信息</div>
        <div class="layui-card-body layui-form-item">
          <div id="carInfo"></div>
          <div id="driverInfo"></div>
        </div>
      </div>
    </div>
    <div class="layui-col-md12">
      <div class="layui-card">
        <div class="layui-card-header">物料信息</div>
        <div class="layui-card-body">
          <table
            class="layui-table"
            id="deliveryRecord-table"
            lay-filter="deliveryRecord-table"
          ></table>
        </div>
      </div>
    </div>
  </div>
</script>

<script type="text/html" id="logistics-view1">
  <div class="layui-row layui-col-space15">
    <div class="layui-col-md12">
      <div class="layui-card">
        <div class="layui-card-header">供应商信息</div>
        <div class="layui-card-body layui-form-item" id="supplierInfo"></div>
      </div>
    </div>
    <div class="layui-col-md12">
      <div class="layui-card">
        <div class="layui-card-header">物料信息</div>
        <div class="layui-card-body">
          <table
            class="layui-table"
            id="deliveryRecord-table"
            lay-filter="deliveryRecord-table"
          ></table>
        </div>
      </div>
    </div>
  </div>
</script>

<script type="text/html" id="logistics-progress">
  <fieldset
    class="layui-elem-field layui-field-title"
    style="margin-top: 30px;"
  >
    <legend>物流进度</legend>
  </fieldset>
  <ul
    class="layui-timeline"
    id="logisticsProgress"
    style="padding: 0 30px;"
  ></ul>
</script>

<script type="text/html" id="logistics-info">
  <div style="padding: 40px 20px">
    <div class="layui-form-item">
      <label class="layui-form-label">快递100地址</label>
      <div class="layui-input-block">
        <input
          type="text"
          value="https://www.kuaidi100.com"
          class="layui-input"
          disabled="disabled"
          style="border: 0px"
        />
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">物流公司</label>
      <div class="layui-input-block">
        <input
          id="company"
          type="text"
          class="layui-input"
          disabled="disabled"
          style="border: 0px"
        />
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">物流单号</label>
      <div class="layui-input-block">
        <input
          id="sn"
          type="text"
          class="layui-input"
          disabled="disabled"
          style="border: 0px"
        />
      </div>
    </div>
  </div>
</script>

<script type="text/html" id="supplier_info">
  <div class="layui-col-md4">编码：{{null != d.code ? d.code : ""}}</div>
  <div class="layui-col-md4">
    名称：{{null != d.corporateName ? d.corporateName : ""}}
  </div>
  <div class="layui-col-md4">
    财务联系人：{{null != d.financialContact ? d.financialContact : ""}}
  </div>
  <div class="layui-col-md4">
    财务联系人电话：{{null != d.financialContactPhone ? d.financialContactPhone
    : ""}}
  </div>
  <div class="layui-col-md4">
    业务联系人：{{null != d.businessContact ? d.businessContact : ""}}
  </div>
  <div class="layui-col-md4">
    业务联系人电话：{{null != d.businessContactPhone ? d.businessContactPhone :
    ""}}
  </div>
  <div class="layui-col-md4">
    法人：{{null != d.legalPerson ? d.legalPerson : ""}}
  </div>
  <div class="layui-col-md4">
    法人电话：{{null != d.legalPersonPhone ? d.legalPersonPhone : ""}}
  </div>
  <div class="layui-col-md4">
    详细地址：{{null != d.address ? d.address : ""}}
  </div>
</script>

<script type="text/html" id="car_info">
  <div class="layui-col-md4">车牌号：{{d.carNumber}}</div>
  <div class="layui-col-md4">运输公司名称：{{d.transCompanyName}}</div>
  <div class="layui-col-md4">运输公司电话：{{d.transCompanyPhone}}</div>
  <div class="layui-col-md4">载重：{{d.loadHeavy}}吨</div>
  <div class="layui-col-md4">车辆型号：{{d.emissionStandards}}</div>
  <div class="layui-col-md4">是否超长车辆：{{d.isLong == 1 ? '是' : '否'}}</div>
</script>

<script type="text/html" id="driver_info">
  <div class="layui-col-md4">司机名称：{{d.driverName}}</div>
  <div class="layui-col-md4">司机身份证号：{{d.driverIdCardNum}}</div>
  <div class="layui-col-md4">司机电话：{{d.driverPhone}}</div>
</script>

<script type="text/html" id="logistics_progress">
  <!-- {{# if(d.length > 0){ }} {{# layui.each(d, function(index, item){ }} -->
  <li class="layui-timeline-item">
    <i class="layui-icon layui-timeline-axis"></i>
    <div class="layui-timeline-content layui-text">
      <h3 class="layui-timeline-title">{{item.createTime}}</h3>
      <p style="color: #009688;">{{item.name}}</p>
      <p>{{item.remark ? item.remark : ''}}</p>
    </div>
  </li>
  <!-- {{# }) }} {{# }else{ }} 暂无数据 {{# } }} -->
</script>
<!--打印采购单弹窗-->
<script type="text/html" id="printPurchaseOrderTemplate">
  <form
    lay-filter="printPurchaseOrderTemplateForm"
    class="layui-form open-form printTemplateForm"
  >
    <div class="open-model">
      <div class="open-auto">
        <div class="my-print-box" id="printHtml"></div>
      </div>
      <div class="layui-form-item text-right">
        <button
          class="layui-btn layui-btn-primary"
          type="button"
          ew-event="closeDialog"
        >
          取消
        </button>
        <button class="layui-btn" type="button" id="printPurchaseOrder">
          打印
        </button>
      </div>
    </div>
  </form>
</script>
<!--<script type="text/javascript" src="../../assets/libs/qrcode.min.js"></script>-->
<!-- js部分 -->
<script src="/admin/assets/libs/jquery/jquery-3.2.1.min.js"></script>
<script src="/admin/assets/libs/jquery/jQuery.print.js.js"></script>
<script>
  layui.use(
    ["layer", "form", "table", "admin", "laytpl", "laydate", "util"],
    function () {
      var $ = layui.jquery;
      var layer = layui.layer;
      var form = layui.form;
      var table = layui.table;
      var config = layui.config;
      var admin = layui.admin;
      var upload = layui.upload;
      var laytpl = layui.laytpl;
      var laydate = layui.laydate;
      var util = layui.util;
      let nowData = {};
      if (typeof parentData !== "undefined") {
        nowData = { ...parentData };
      }
      if (nowData.eventName == "radio") {
        $("#erpPurchaseOrder-btn-add").hide();
        $("#confirmSelectBtn").show();
      }

      form.render("select");
      admin.selectSearch();

      //时间范围
      laydate.render({
        elem: "#pTime",
        type: "date",
        range: true,
        done: function (value, date, endDate) {
          if (value) {
            var dateValue = value.split(" - ");
            $("#sTime").val(dateValue[0] + " 00:00:00");
            $("#eTime").val(dateValue[1] + " 23:59:59");
          } else {
            $("#sTime").val("");
            $("#eTime").val("");
          }
          setTimeout(function () {
            $('[lay-filter="formSubSearchLog"]').click();
          }, 300);
        },
      });

      // 获取供应商
      admin.initDataSelect(
        "enterprise/purchase/admin/supplierInfoPass/list",
        { limit: 99999 },
        "querySupplierId",
        null,
        "供应商",
        "corporateName",
        null
      );

      // 获取部门
      admin.initDataSelectTree(
        true,
        "user/admin/role/getTreeData",
        null,
        "selectDepartmentQuery",
        null,
        "部门",
        "queryDepartmentId",
        function (data) {
          //清空申请人列表
          $("#queryPersonnelId").empty();
          // 获取申请人
          var roleId = data.change[0].value;
          admin.initDataSelect(
            "user/admin/user/list",
            {
              limit: 9999,
              departmentId: roleId,
            },
            "queryPersonnelId",
            null,
            "申请人",
            "nickname",
            null
          );
        }
      );

      //状态
      admin.getDictList("status", "sys_audit_status", null, "审核状态");

      // 渲染表格
      var insTb = table.render({
        elem: "#erpPurchaseOrder-table",
        url: config.base + "enterprise/purchase/admin/purchaseOrder/list",
        where: { ...(nowData.where ? nowData.where : {}) },
        toolbar: true,
        defaultToolbar: ["filter"],
        page: true,
        cellMinWidth: 100,
        cols: [
          [
            {
              type: "radio",
              hide: nowData.eventName != "radio",
            },
            { type: "numbers", title: "序号", fixed: "left" },
            { field: "sn", align: "center", title: "订单编号", width: 150 },
            {
              field: "productNum",
              align: "center",
              title: "物料数量",
              width: 100,
            },
            {
              field: "productNames",
              align: "center",
              title: "物料名称",
              width: 140,
            },
            {
              field: "corporateName",
              align: "center",
              title: "供应商",
              width: 120,
            },
            { field: "statusDesc", align: "center", title: "状态", width: 100 },
            {
              field: "shippingStatusDesc",
              align: "center",
              title: "发货状态",
              width: 100,
            },
            // {field: 'purchaseTypeName', align: 'center', title: '采购类型',width:120, fixed: 'left'},
            // {field: 'emergencyDegreeName', align: 'center', title: '紧急程度',width:120, fixed: 'left'},
            {
              field: "businessContactName",
              align: "center",
              title: "供应商联系人",
              width: 100,
            },
            {
              field: "creatorName",
              align: "center",
              title: "制单人",
              width: 120,
            },
            {
              field: "auditorNickname",
              align: "center",
              title: "审核人",
              width: 120,
            },
            //  {field: 'changerNickname', align: 'center', title: '变更人', width: 120},
            {
              field: "createTime",
              align: "center",
              title: "创建时间",
              width: 170,
            },
            {
              align: "center",
              toolbar: "#erpPurchaseOrder-table-bar",
              title: "操作",
              width: 320,
              fixed: "right",
              hide: nowData.eventName == "radio",
            },
          ],
        ],
      });

      // 添加按钮点击事件
      $("#erpPurchaseOrder-btn-add").click(function () {
        openForm("add");
        // showEditModel();
      });

      $("#confirmSelectBtn").click(function () {
        let list = table.checkStatus("erpPurchaseOrder-table").data;
        childData.list = list;
        layer.close(nowData.zindex);
      });

      // 打印采购单
      function showPrintPurchaseOrderTemplate(data) {
        admin.open({
          type: 1,
          area: ["1060px", "800px"],
          offset: "65px",
          title: "采购订单",
          content: $("#printPurchaseOrderTemplate").html(),
          success: function () {
            let html = "";
            admin.req(
              "enterprise/purchase/admin/purchaseOrderDetail/list",
              { purchaseOrderId: data.id },
              (res) => {
                if (res.code === 200) {
                  html += `<div class="print-title">采购订单</div>
          <div class="flexCt print-tip-info">
            <div class="company">公司：${config.getTempData(
              "companyName"
            )}</div>
            <div class="time">${data.createTime}</div>
          </div>
          <div class="print-table">
            <div class="print-view">
              <div class="print-nape ">
                <div class="cell">
                  <div class="name w-120 justify">供应商：</div>
                  <div class="val flex-1">${data.corporateName}</div>
                </div>
                <div class="cell">
                  <div class="name w-120">联系人：</div>
                  <div class="val flex-1">${data.businessContactName}</div>
                </div>
              </div>
              <div class="print-nape">
                <div class="cell">
                  <div class="name w-120">电话：</div>
                  <div class="val flex-1"></div>
                </div>
                <div class="cell">
                  <div class="name w-120">采购单号：</div>
                  <div class="val flex-1">${data.sn}</div>
                </div>
              </div>
              <div class="print-nape">
                <div class="cell">
                  <div class="name w-120">采购类型：</div>
                  <div class="val flex-1">${data.purchaseTypeName}</div>
                </div>
                <div class="cell">
                  <div class="name w-120">紧急程度：</div>
                  <div class="val flex-1">${data.emergencyDegreeName}</div>
                </div>
              </div>
              <div class="print-nape">
                <div class="cell w-100">
                  <div class="name w-120">交货时间：</div>
                  <div class="val flex-1">${data.planDeliverTime}</div>
                </div>
              </div>
              <div class="print-nape">
                <div class="cell w-100">
                  <div class="th v-60" style="padding: 0">序号</div>
                  <div class="th v-160">物料名称</div>
                  <div class="th v-160">物料编号</div>
                  <div class="th v-160">规格型号</div>
                  <div class="th">单位</div>
                  <div class="th">数量</div>
                  <div class="th">单价</div>
                  <div class="th">总价</div>
                  <div class="th">备注</div>
                </div>
              </div>`;
                  let list =
                    res.data.length > 12 ? res.data.slice(0, 12) : res.data;
                  let fillValue = {},
                    allMoney = new Decimal(0);
                  let filledArray = [
                    ...list,
                    ...Array.from(
                      { length: 12 - list.length },
                      () => fillValue
                    ),
                  ];
                  filledArray.forEach((item, index) => {
                    if (item.totalAmount) {
                      allMoney = allMoney.add(new Decimal(item.totalAmount));
                    }
                    html += `<div class="print-nape">
                    <div class="cell w-100">
                      <div class="td v-60" style="padding: 0">${index + 1}</div>
                      <div class="td v-160">${item.productName || ""}</div>
                      <div class="td v-160">${item.skuCode || ""}</div>
                      <div class="td v-160">${item.specifications || ""}</div>
                      <div class="td">${item.unitName || ""}</div>
                      <div class="td">${item.quantity || ""}</div>
                      <div class="td">${item.taxPrice || ""}</div>
                      <div class="td">${item.totalAmount || ""}</div>
                      <div class="td">${item.remark || ""}</div>
                    </div>
                  </div>`;
                  });
                  html += `<div class="print-nape">
                <div class="cell w-100">
                  <div class="name w-120">合计：</div>
                  <div class="val flex-1 lt">人民币：${allMoney.toFixed(
                    2
                  )}</div>
                </div>
              </div>
              <div class="print-nape">
                <div class="cell w-100">
                  <div class="name v-60">
                    <span style="width: 15px;">备注</span>
                  </div>
                  <div class="val flex-1" style="justify-content: flex-start;padding-bottom: 25px;">
                    1、供应厂商必须在收到本公司采购单后24小时内签名和盖公司印章传真回本厂，否则视为默认。<br/>
                    2、供应厂商必须确实遵照订单之交期或本公司修正之交期，若有延误必须书面通知本公司。<br/>
                    3、供应厂商未能如期交货，影响本公司生产或品质不符及未经本公司同意办更任何条款，本公司有权取消订单。<br/>
                    4、供应厂商送货单上必须规范书写本公司采购单之订单编号、物料编号、物料名称、规格型号，否则本公司有权退单。<br/>
                    5、其它未尽事宜,遵照《购货协议》执行。
                  </div>
                </div>
              </div>
              <div class="print-nape nape-btm">
                <div class="btm-sign lt">负责人签名与盖公司印章：</div>
                <div class="sign-rt flex-1">
                  <div class="cell w-100">
                    <div class="name flex-1">制单人</div>
                    <div class="name flex-1">审核人</div>
                  </div>
                  <div class="cell w-100">
                    <div class="val flex-1">${data.creatorName}</div>
                    <div class="val flex-1">${data.auditorNickname}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>`;
                  $("#printHtml").html(html);

                  $("#printPurchaseOrder").click(function () {
                    $("#printHtml").print({
                      debug: false,
                      importCSS: true,
                      printContainer: true,
                      operaSupport: false,
                    });
                  });
                }
              },
              "get"
            );
          },
        });
      }

      function openForm(eventName, data) {
        const titleobj = {
          add: "新增采购订单",
          edit: "修改采购订单",
          view: "查看采购订单",
          audit: "审核采购订单",
          generate: "生成入库单",
          logistics: "物流跟踪",
        };
        admin.formOpen({
          title: titleobj[eventName],
          area: ["90%", "80%"],
          offset: "50px",
          path: "components/purchase/purchaseOrderForm.html",
          success: function () {
            parentData.data = data;
            parentData.eventName = eventName;
          },
        });
      }

      // 工具条点击事件
      table.on("tool(erpPurchaseOrder-table)", function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === "edit") {
          // 修改
          // showEditModel(data, layEvent);
          admin.req(
            "enterprise/purchase/admin/purchaseOrderDetail/list",
            { purchaseOrderId: data.id },
            (res) => {
              if (res.code === 200) {
                let dataVal = { ...data };
                dataVal.list = res.data;
                openForm("edit", dataVal);
              }
            }
          );
        } else if (obj.event === "del") {
          //删除
          doDelete(obj);
        } else if (obj.event === "audit") {
          //审核
          showEditModel(data, layEvent);
          // admin.req('enterprise/purchase/admin/purchaseOrderDetail/list', {purchaseOrderId: data.id}, (res) => {
          //     if (res.code === 200) {
          //         let dataVal = {...data}
          //         dataVal.list = res.data
          //         openForm('edit', dataVal);
          //     }
          // })
        } else if (obj.event === "generate") {
          //生成入库单
          generate(data);
        } else if (obj.event === "close") {
          //关闭
          doClose(obj);
        } else if (obj.event === "view") {
          //详情
          // showViewModel(data,layEvent);
          console.log("data", data);
          admin.req(
            "enterprise/purchase/admin/purchaseOrderDetail/list",
            { purchaseOrderId: data.id },
            (res) => {
              if (res.code === 200) {
                let dataVal = { ...data };
                dataVal.list = res.data;
                openForm("view", dataVal);
              }
            }
          );
        } else if (obj.event === "logistics") {
          //物流
          logistics(data);
        } else if (obj.event === "print") {
          showPrintPurchaseOrderTemplate(data);
        }
      });

      //显示表单弹窗
      var showEditModel = function (data, layEvent) {
        var title = data
          ? layEvent == "audit"
            ? "审核采购订单信息"
            : "更新采购订单信息"
          : "新增采购订单信息";
        var $html = data
          ? $("#erpPurchaseOrder-edit").html()
          : $("#erpPurchaseOrder-form").html();
        admin.open({
          type: 1,
          area: ["80%", "85%"],
          title: title,
          content: $html,
          success: function () {
            // 获取采购类型
            //admin.initDataSelect('enterprise/purchase/admin/purchaseType/list',{limit: 99999},"purchaseType",data ? data.purchaseType : null,"采购类型","purchaseTypeName",null);

            // 获取紧急程度
            admin.initDataSelect(
              "enterprise/purchase/admin/purchaseUrgency/list",
              { limit: 99999 },
              "emergencyDegree",
              data ? data.emergencyDegree : null,
              "紧急程度",
              "purchaseUrgencyName",
              null
            );

            // 获取供应商联系人
            //admin.initDataSelect('enterprise/purchase/admin/supplierContacts/list',{limit: 99999},"businessContact",data ? data.contactName : null,"供应商联系人","contactName",null);

            // 获取供应商
            admin.initDataSelect(
              "enterprise/purchase/admin/supplierInfoPass/list",
              { limit: 9999 },
              "supplierId",
              null,
              "供应商",
              "corporateName",
              null
            );

            //供应商选择事件
            form.on("select(supplierId)", function (data) {
              $("#businessContact").empty();
              //供应商联系人列表
              admin.initDataSelect(
                "enterprise/purchase/admin/supplierContacts/list",
                {
                  limit: 9999,
                  corporateId: data.value,
                },
                "businessContact",
                data ? data.contactName : null,
                "供应商联系人",
                "contactName",
                null
              );
            });
            $("#contractIdSelect").hide();
            form.on("select(hasSign)", function (data) {
              if (data.value == 1) {
                $("#contractIdSelect").show();
                $("#contractId").empty();
                // 选择合同
                admin.initDataSelect(
                  "enterprise/sell/admin/agentContract/list",
                  { status: 1 },
                  "contractId",
                  null,
                  "合同"
                );
              } else {
                $("#contractId").empty();
                // 选择合同
                admin.initDataSelect(
                  "enterprise/sell/admin/agentContract/list",
                  { status: 1 },
                  "contractId",
                  null,
                  "合同"
                );
                $("#contractIdSelect").hide();
              }
            });
            //采购类型选择事件
            let selectMap = new Map();
            admin.initDataSelectAndMap(
              "enterprise/purchase/admin/purchaseType/list",
              { limit: 9999 },
              "purchaseType",
              data ? data.purchaseType : null,
              "采购类型",
              "purchaseTypeName",
              "id",
              selectMap
            );

            form.on("select(purchaseType)", function (data) {
              let val = data.value;
              if (val) {
                let dataInfo = selectMap.get(val);
                console.log(dataInfo);
                $("#departmentName").val(dataInfo.department);
                $("#departmentId").val(dataInfo.departmentId);

                $("#postId").val(dataInfo.stations);

                console.log(dataInfo.departmentId);
                $("#auditor").empty();
                admin.initDataSelect(
                  "user/admin/user/list",
                  {
                    limit: 9999,
                    departmentId: dataInfo.departmentId,
                  },
                  "auditor",
                  data ? data.auditor : null,
                  "订单审核人",
                  "nickname",
                  null
                );
              } else {
                $("#departmentId").val();
                form.render("select");
              }
            });

            if (data) {
              var dataList = [];
              var purchaseOrderDetails = []; //明细数据
              var usualData = [];
              var codeArr = []; //物料选择集合
              //自定义验证规则
              form.verify({
                quantity: [
                  /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][0-9][1-9]|[1-9]\d{0,1})))|[ \t]*)$/,
                  "格式错误",
                ],
                rate: [
                  /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1})))|[ \t]*)$/,
                  "格式错误",
                ],
              });

              var status = data.status;
              if (status == "stayAudit" && layEvent == "audit") {
                $("#audit").show();
                form.on("radio(getStatus)", function (data) {
                  if (data.value == "fail") {
                    $("#reason").show();
                  } else {
                    $("#reason").hide();
                    $("textarea[name='reason']").val("");
                  }
                });
              } else if (status == "success") {
                $("#viewAudit").show();
                $("#viewAudit")
                  .find("textarea")
                  .val(data.reason)
                  .attr("readonly", true);
              }
              // 获取供应商
              admin.initDataSelect(
                "enterprise/purchase/admin/supplierInfoPass/list",
                { limit: 99999 },
                "supplierId",
                data.supplierId,
                "供应商",
                "corporateName",
                null
              );

              // 获取部门
              admin.initDataSelectTree(
                true,
                "user/admin/role/getTreeData",
                null,
                "selectDepartmentEdit",
                data.departmentId,
                "部门",
                "departmentId",
                function (data) {
                  //清空申请人列表
                  $("#personnelId").empty();
                  // 获取申请人
                  var roleId = data.change[0].value;
                  admin.initDataSelect(
                    "user/admin/user/list",
                    {
                      limit: 9999,
                      departmentId: roleId,
                    },
                    "personnelId",
                    null,
                    "申请人",
                    "nickname",
                    null
                  );
                }
              );

              // 获取申请人
              admin.initDataSelect(
                "user/admin/user/list",
                {
                  limit: 9999,
                  departmentId: data.departmentId,
                },
                "personnelId",
                data.personnelId,
                "申请人",
                "nickname",
                null
              );

              //获取明细数据
              admin.req(
                "enterprise/purchase/admin/purchaseOrderDetail/list",
                { purchaseOrderId: data.id },
                function (data) {
                  if (200 == data.code) {
                    var detail = data.data;
                    for (var i = 0; i < detail.length; i++) {
                      dataList.push({});
                      dataList[i].id = detail[i].id;
                      dataList[i].skuCode = detail[i].skuCode;
                      dataList[i].skuName = detail[i].productName;
                      dataList[i].mainUnitName = detail[i].unitName;
                      dataList[i].skuSpec = detail[i].specifications
                        ? detail[i].specifications
                        : "";
                      dataList[i].quantity = detail[i].quantity
                        ? detail[i].quantity
                        : "";
                      dataList[i].rate = detail[i].rate ? detail[i].rate : "";
                      dataList[i].taxPrice = detail[i].taxPrice
                        ? detail[i].taxPrice
                        : "";
                      dataList[i].price = detail[i].price
                        ? detail[i].price
                        : "";
                      dataList[i].amount = detail[i].amount
                        ? detail[i].amount
                        : "";
                      dataList[i].tax = detail[i].tax ? detail[i].tax : "";
                      dataList[i].totalAmount = detail[i].totalAmount
                        ? detail[i].totalAmount
                        : "";
                      purchaseOrderDetails.push({});
                      purchaseOrderDetails[i].id = detail[i].id;
                      purchaseOrderDetails[i].skuCode = detail[i].skuCode;
                      purchaseOrderDetails[i].skuName = detail[i].productName;
                      purchaseOrderDetails[i].mainUnitName = detail[i].unitName;
                      purchaseOrderDetails[i].skuSpec = detail[i].specifications
                        ? detail[i].specifications
                        : "";
                      purchaseOrderDetails[i].quantity = detail[i].quantity
                        ? detail[i].quantity
                        : "";
                      purchaseOrderDetails[i].rate = detail[i].rate
                        ? detail[i].rate
                        : "";
                      purchaseOrderDetails[i].taxPrice = detail[i].taxPrice
                        ? detail[i].taxPrice
                        : "";
                      purchaseOrderDetails[i].price = detail[i].price
                        ? detail[i].price
                        : "";
                      purchaseOrderDetails[i].amount = detail[i].amount
                        ? detail[i].amount
                        : "";
                      purchaseOrderDetails[i].tax = detail[i].tax
                        ? detail[i].tax
                        : "";
                      purchaseOrderDetails[i].totalAmount = detail[i]
                        .totalAmount
                        ? detail[i].totalAmount
                        : "";
                      usualData.push({});
                      usualData[i].quantity = detail[i].quantity
                        ? detail[i].quantity
                        : "";
                      usualData[i].rate = detail[i].rate ? detail[i].rate : "";
                      usualData[i].taxPrice = detail[i].taxPrice
                        ? detail[i].taxPrice
                        : "";
                      usualData[i].price = detail[i].price
                        ? detail[i].price
                        : "";
                      usualData[i].amount = detail[i].amount
                        ? detail[i].amount
                        : "";
                      usualData[i].tax = detail[i].tax ? detail[i].tax : "";
                      usualData[i].totalAmount = detail[i].totalAmount
                        ? detail[i].totalAmount
                        : "";
                      codeArr.push(detail[i].skuCode);
                    }
                    //dataList.push({},{},{},{},{},{},{},{},{},{});
                    usualData.push({});
                    if (layEvent === "edit") {
                      dataList.push({});
                    }

                    // 渲染表格
                    if (layEvent === "edit") {
                      table.render({
                        elem: "#erpPurchaseOrder-add-table",
                        data: dataList,
                        limit: dataList.length,
                        cellMinWidth: 100,
                        cols: [
                          [
                            { type: "numbers", title: "序号", fixed: "left" },
                            {
                              field: "skuName",
                              align: "center",
                              title:
                                "物料名称<span style='color: red'>*</span>",
                              templet:
                                '<div><span class="erpInventoryId" style="display: block;cursor: pointer;" data-add="{{d.skuName != null ? false : true}}">{{d.skuName != null ? d.skuName : "请选择物料"}}</span></div>',
                              width: "150",
                            },
                            {
                              field: "skuCode",
                              align: "center",
                              title:
                                "物料编号<span style='color: red'>*</span>",
                              width: 140,
                            },
                            {
                              field: "skuSpec",
                              align: "center",
                              title: "规格型号",
                            },
                            {
                              field: "mainUnitName",
                              align: "center",
                              title: "采购单位",
                            },
                            {
                              field: "quantity",
                              align: "center",
                              title: "数量<span style='color: red'>*</span>",
                              templet: "#quantity",
                              width: 140,
                            },
                            {
                              field: "rate",
                              align: "center",
                              title: "税率(%)<span style='color: red'>*</span>",
                              templet: "#rate",
                              width: 140,
                            },
                            {
                              field: "taxPrice",
                              align: "center",
                              title:
                                "含税单价<span style='color: red'>*</span>",
                              templet: "#taxPrice",
                              width: 140,
                            },
                            {
                              field: "price",
                              align: "center",
                              title: "单价<span style='color: red'>*</span>",
                            },
                            // {
                            //     field: 'amount',
                            //     align: 'center',
                            //     title: "金额<span style='color: red'>*</span>"
                            // },
                            // {
                            //     field: 'tax',
                            //     align: 'center',
                            //     title: "税额<span style='color: red'>*</span>"
                            // },
                            // {
                            //     field: 'totalAmount',
                            //     align: 'center',
                            //     title: "合计金额<span style='color:red;'>*</span>"
                            // },
                            {
                              align: "center",
                              fixed: "right",
                              toolbar: "#erpPurchaseOrder-add-table-bar",
                              title: "操作",
                              width: 110,
                            },
                          ],
                        ],
                        done: function () {
                          $("input[name='quantity']").on("input", function (e) {
                            //获取input输入的值
                            var curValue = e.delegateTarget.value;
                            var curIndex = $(this).closest("tr").data("index");
                            if (purchaseOrderDetails[curIndex]) {
                              purchaseOrderDetails[curIndex].quantity =
                                curValue;
                            }
                            dataList[curIndex].quantity = curValue;
                            usualData[curIndex].quantity = curValue;
                            if (usualData.length - curIndex - 1 < 10) {
                              var addLength =
                                10 - (usualData.length - curIndex - 1);
                              for (var i = 0; i < addLength; i++) {
                                usualData.push({});
                              }
                            }
                            var rate = "";
                            var taxPrice = "";
                            $(this)
                              .closest("tr")
                              .find("td")
                              .each(function () {
                                if ($(this).data("field") == "rate") {
                                  rate = $(this).find("input").val();
                                }
                                if ($(this).data("field") == "taxPrice") {
                                  taxPrice = $(this).find("input").val();
                                }
                              });
                            //计算价格
                            calculatePrice(
                              curValue,
                              rate,
                              taxPrice,
                              $(this),
                              curIndex
                            );
                          });
                          $("input[name='rate']").on("input", function (e) {
                            //获取input输入的值
                            var curValue = e.delegateTarget.value;
                            var curIndex = $(this).closest("tr").data("index");
                            if (purchaseOrderDetails[curIndex]) {
                              purchaseOrderDetails[curIndex].rate = curValue;
                            }
                            dataList[curIndex].rate = curValue;
                            usualData[curIndex].rate = curValue;
                            if (usualData.length - curIndex - 1 < 10) {
                              var addLength =
                                10 - (usualData.length - curIndex - 1);
                              for (var i = 0; i < addLength; i++) {
                                usualData.push({});
                              }
                            }
                            var quantity = "";
                            var taxPrice = "";
                            $(this)
                              .closest("tr")
                              .find("td")
                              .each(function () {
                                if ($(this).data("field") == "quantity") {
                                  quantity = $(this).find("input").val();
                                }
                                if ($(this).data("field") == "taxPrice") {
                                  taxPrice = $(this).find("input").val();
                                }
                              });
                            //计算价格
                            calculatePrice(
                              quantity,
                              curValue,
                              taxPrice,
                              $(this),
                              curIndex
                            );
                          });
                          $("input[name='taxPrice']").on("input", function (e) {
                            //获取input输入的值
                            var curValue = e.delegateTarget.value;
                            var curIndex = $(this).closest("tr").data("index");
                            if (purchaseOrderDetails[curIndex]) {
                              purchaseOrderDetails[curIndex].taxPrice =
                                curValue;
                            }
                            dataList[curIndex].taxPrice = curValue;
                            usualData[curIndex].taxPrice = curValue;
                            if (usualData.length - curIndex - 1 < 10) {
                              var addLength =
                                10 - (usualData.length - curIndex - 1);
                              for (var i = 0; i < addLength; i++) {
                                usualData.push({});
                              }
                            }
                            var quantity = "";
                            var rate = "";
                            $(this)
                              .closest("tr")
                              .find("td")
                              .each(function () {
                                if ($(this).data("field") == "quantity") {
                                  quantity = $(this).find("input").val();
                                }
                                if ($(this).data("field") == "rate") {
                                  rate = $(this).find("input").val();
                                }
                              });
                            //计算价格
                            calculatePrice(
                              quantity,
                              rate,
                              curValue,
                              $(this),
                              curIndex
                            );
                          });

                          //通过数量、税率、含税单价计算价格
                          function calculatePrice(
                            quantity,
                            rate,
                            taxPrice,
                            $cur,
                            curIndex
                          ) {
                            purchaseOrderDetails = purchaseOrderDetails.filter(
                              (item) =>
                                item.skuCode !== undefined &&
                                item.skuCode !== null
                            );
                            //计算单价
                            if (rate != "" && taxPrice != "") {
                              var price =
                                (taxPrice * 100) / (Number(rate) + 100);
                              $cur
                                .closest("tr")
                                .find("td")
                                .each(function () {
                                  if ($(this).data("field") == "price") {
                                    $(this).find("div").text(price.toFixed(2));
                                    dataList[curIndex].price = price.toFixed(2);
                                    usualData[curIndex].price =
                                      price.toFixed(2);
                                    if (purchaseOrderDetails[curIndex]) {
                                      purchaseOrderDetails[curIndex].price =
                                        price.toFixed(2);
                                    }
                                  }
                                });
                            } else {
                              $cur
                                .closest("tr")
                                .find("td")
                                .each(function () {
                                  if ($(this).data("field") == "price") {
                                    $(this).find("div").text("");
                                    dataList[curIndex].price = "";
                                    usualData[curIndex].price = "";
                                    if (purchaseOrderDetails[curIndex]) {
                                      purchaseOrderDetails[curIndex].price = "";
                                    }
                                  }
                                });
                            }
                            //计算金额
                            if (
                              quantity != "" &&
                              rate != "" &&
                              taxPrice != ""
                            ) {
                              var amount =
                                (quantity * taxPrice * 100) /
                                (Number(rate) + 100);
                              $cur
                                .closest("tr")
                                .find("td")
                                .each(function () {
                                  if ($(this).data("field") == "amount") {
                                    $(this).find("div").text(amount.toFixed(2));
                                    dataList[curIndex].amount =
                                      amount.toFixed(2);
                                    usualData[curIndex].amount =
                                      amount.toFixed(2);
                                    if (purchaseOrderDetails[curIndex]) {
                                      purchaseOrderDetails[curIndex].amount =
                                        amount.toFixed(2);
                                    }
                                  }
                                });
                            } else {
                              $cur
                                .closest("tr")
                                .find("td")
                                .each(function () {
                                  if ($(this).data("field") == "amount") {
                                    $(this).find("div").text("");
                                    dataList[curIndex].amount = "";
                                    usualData[curIndex].amount = "";
                                    if (purchaseOrderDetails[curIndex]) {
                                      purchaseOrderDetails[curIndex].amount =
                                        "";
                                    }
                                  }
                                });
                            }
                            //计算税额
                            if (
                              quantity != "" &&
                              rate != "" &&
                              taxPrice != ""
                            ) {
                              var tax =
                                quantity * taxPrice -
                                (quantity * taxPrice * 100) /
                                  (Number(rate) + 100);
                              $cur
                                .closest("tr")
                                .find("td")
                                .each(function () {
                                  if ($(this).data("field") == "tax") {
                                    $(this).find("div").text(tax.toFixed(2));
                                    dataList[curIndex].tax = tax.toFixed(2);
                                    usualData[curIndex].tax = tax.toFixed(2);
                                    if (purchaseOrderDetails[curIndex]) {
                                      purchaseOrderDetails[curIndex].tax =
                                        tax.toFixed(2);
                                    }
                                  }
                                });
                            } else {
                              $cur
                                .closest("tr")
                                .find("td")
                                .each(function () {
                                  if ($(this).data("field") == "tax") {
                                    $(this).find("div").text("");
                                    dataList[curIndex].tax = "";
                                    usualData[curIndex].tax = "";
                                    if (purchaseOrderDetails[curIndex]) {
                                      purchaseOrderDetails[curIndex].tax = "";
                                    }
                                  }
                                });
                            }
                            //计算合计金额
                            if (quantity != "" && taxPrice != "") {
                              var totalAmount = quantity * taxPrice;
                              $cur
                                .closest("tr")
                                .find("td")
                                .each(function () {
                                  if ($(this).data("field") == "totalAmount") {
                                    $(this)
                                      .find("div")
                                      .text(totalAmount.toFixed(2));
                                    dataList[curIndex].totalAmount =
                                      totalAmount.toFixed(2);
                                    usualData[curIndex].totalAmount =
                                      totalAmount.toFixed(2);
                                    if (purchaseOrderDetails[curIndex]) {
                                      purchaseOrderDetails[
                                        curIndex
                                      ].totalAmount = totalAmount.toFixed(2);
                                    }
                                  }
                                });
                            } else {
                              $cur
                                .closest("tr")
                                .find("td")
                                .each(function () {
                                  if ($(this).data("field") == "totalAmount") {
                                    $(this).find("div").text("");
                                    dataList[curIndex].totalAmount = "";
                                    usualData[curIndex].totalAmount = "";
                                    if (purchaseOrderDetails[curIndex]) {
                                      purchaseOrderDetails[
                                        curIndex
                                      ].totalAmount = "";
                                    }
                                  }
                                });
                            }
                          }

                          layer.closeAll("loading");
                          $(".erpInventoryId").each(function (index) {
                            $(this).click(function () {
                              let list = purchaseOrderDetails;
                              let skuCodes = list
                                .filter((item) => item.skuCode !== undefined)
                                .map((item) => item.skuCode);
                              let infos = skuCodes.join(",");
                              /*var isWeigh = $("select[name='isWeigh']").val();
                                                if(isWeigh != "") {*/
                              var isAdd = $(this).data("add");
                              //获取物料数据
                              var erpInventoryList = layer.open({
                                type: 1,
                                title: "物料列表",
                                area: ["1100px", "700px"],
                                offset: "120px",
                                content: $("#erpInventoryList").html(),
                                success: function () {
                                  form.render("select");

                                  // 请求物料分类
                                  let arr2tree;
                                  admin.reqSync(
                                    "enterprise/product/admin/productCategory/getProductCategoryByType",
                                    { type: 0 },
                                    function (res) {
                                      for (
                                        let i = 0;
                                        i < res.data.length;
                                        i++
                                      ) {
                                        res.data[i].children = [];
                                      }
                                      arr2tree = xmSelect.arr2tree(
                                        res.data,
                                        "parentId",
                                        "id",
                                        "children",
                                        -1
                                      );
                                    },
                                    "get",
                                    false
                                  );

                                  let smlSelectInstans = xmSelect.render({
                                    el: "#addSelfCollectedGoodsProductCategoryId",
                                    model: { label: { type: "text" } },
                                    radio: true,
                                    clickClose: true,
                                    filterable: true,
                                    tree: {
                                      show: true,
                                      strict: false,
                                      expandedKeys: [-1],
                                    },
                                    tips: "请选择物料类别",
                                    prop: {
                                      name: "name",
                                      value: "id",
                                      children: "children",
                                    },
                                    data() {
                                      //填充数据
                                      return arr2tree;
                                    },
                                    on(data) {
                                      let parentId =
                                        data.arr.length > 0
                                          ? data.change[0].id
                                          : "";
                                      $(
                                        "input[name='addSelfCollectedGoodsProductCategoryId']"
                                      ).val(parentId);
                                    },
                                  });

                                  var codes = "";
                                  for (var i = 0; i < codeArr.length; i++) {
                                    if (i == 0) {
                                      codes = '"' + codeArr[i] + '"';
                                    } else {
                                      codes += "," + '"' + codeArr[i] + '"';
                                    }
                                  }

                                  // 渲染表格
                                  table.render({
                                    elem: "#erpInventoryList-table",
                                    url:
                                      config.base +
                                      "enterprise/product/admin/productDetail/list",
                                    method: "GET",
                                    where: {
                                      codes: infos,
                                    },
                                    page: true,
                                    cols: [
                                      [
                                        { type: "checkbox" },
                                        {
                                          field: "skuCode",
                                          align: "center",
                                          title: "物料编号",
                                        },
                                        {
                                          field: "skuName",
                                          align: "center",
                                          title: "物料名称",
                                        },
                                        {
                                          field: "skuSpec",
                                          align: "center",
                                          title: "规格型号",
                                        },
                                        {
                                          field: "productTypeName",
                                          align: "center",
                                          title: "物料类别",
                                        },
                                        {
                                          field: "baseUnitName",
                                          align: "center",
                                          title: "基础单位",
                                        },
                                        {
                                          field: "mainUnitName",
                                          align: "center",
                                          title: "主计量单位",
                                        },
                                        {
                                          field: "mainUnitRate",
                                          align: "center",
                                          title: "主计量单位换算率",
                                        },
                                        {
                                          field: "subUnitName",
                                          align: "center",
                                          title: "辅计量单位",
                                        },
                                        {
                                          field: "subUnitRate",
                                          align: "center",
                                          title: "辅计量单位换算率",
                                        },
                                      ],
                                    ],
                                  });

                                  // 搜索按钮点击事件
                                  $("#erpInventoryList-btn-search").click(
                                    function () {
                                      var name = $(
                                        "#erpInventoryList-name"
                                      ).val();
                                      var code = $(
                                        "#erpInventoryList-code"
                                      ).val();
                                      var skuSpec = $(
                                        "#erpInventoryList-spec"
                                      ).val();
                                      var way = $(
                                        "#erpInventoryList-way"
                                      ).val();
                                      var categoryId = $(
                                        "input[name=addSelfCollectedGoodsProductCategoryId]"
                                      ).val();
                                      table.reload("erpInventoryList-table", {
                                        page: { curr: 1 },
                                        where: {
                                          skuCode: code,
                                          skuName: name,
                                          skuSpec: skuSpec,
                                          pricingMethod: way,
                                          categoryId: categoryId,
                                        },
                                      });
                                    }
                                  );

                                  // 确认选择
                                  $("#erpInventoryList-btn-choose").click(
                                    function () {
                                      var checkStatus = table.checkStatus(
                                        "erpInventoryList-table"
                                      ); //test即为基础参数id对应的值
                                      var dataS = checkStatus.data;
                                      for (var i = 0; i < dataS.length; i++) {
                                        dataS[i].productName = dataS[i].skuName;
                                        dataS[i].skuSpec = dataS[i].skuSpec;
                                      }
                                      if (checkStatus.data.length == 0) {
                                        layer.msg("请选择物料", {
                                          icon: 2,
                                          time: 1000,
                                        });
                                      } else {
                                        layer.close(erpInventoryList);
                                        if (dataList.length >= 10) {
                                          dataList.splice(
                                            dataList.length - 10,
                                            10
                                          );
                                        }
                                        if (!isAdd) {
                                          dataList.splice(index, 1);
                                          usualData.splice(index, 1);
                                          codeArr.splice(index, 1);
                                          for (
                                            var i = 0;
                                            i < dataS.length;
                                            i++
                                          ) {
                                            dataList.splice(
                                              index + i,
                                              0,
                                              dataS[i]
                                            );
                                            usualData.splice(index + i, 0, {});
                                            codeArr.splice(
                                              index + i,
                                              0,
                                              dataS[i].skuCode
                                            );
                                          }
                                        } else {
                                          for (
                                            var i = 0;
                                            i < dataS.length;
                                            i++
                                          ) {
                                            dataList.push(dataS[i]);
                                            usualData.push({});
                                            codeArr.push(dataS[i].skuCode);
                                          }
                                        }
                                        //处理数据并存储
                                        for (
                                          var i = 0;
                                          i < dataList.length;
                                          i++
                                        ) {
                                          if (!purchaseOrderDetails[i]) {
                                            purchaseOrderDetails.push({});
                                          }
                                          purchaseOrderDetails[i].skuCode =
                                            dataList[i].skuCode;
                                          purchaseOrderDetails[i].productName =
                                            dataList[i].skuName;
                                          purchaseOrderDetails[i].unitName =
                                            dataList[i].mainUnitName;
                                          purchaseOrderDetails[
                                            i
                                          ].specifications =
                                            dataList[i].skuSpec;
                                          purchaseOrderDetails[
                                            i
                                          ].productTypeName =
                                            dataList[i].productTypeName;
                                          purchaseOrderDetails[i].mainUnitRate =
                                            dataList[i].mainUnitRate;
                                          purchaseOrderDetails[i].subUnitName =
                                            dataList[i].subUnitName;
                                          purchaseOrderDetails[i].subUnitRate =
                                            dataList[i].subUnitRate;

                                          purchaseOrderDetails[i].productName =
                                            dataList[i].skuName;
                                          purchaseOrderDetails[
                                            i
                                          ].specifications =
                                            dataList[i].skuSpec;

                                          if (usualData[i]) {
                                            dataList[i].quantity = usualData[i]
                                              .quantity
                                              ? usualData[i].quantity
                                              : "";
                                            dataList[i].rate = usualData[i].rate
                                              ? usualData[i].rate
                                              : "";
                                            dataList[i].taxPrice = usualData[i]
                                              .taxPrice
                                              ? usualData[i].taxPrice
                                              : "";
                                            dataList[i].price = usualData[i]
                                              .price
                                              ? usualData[i].price
                                              : "";
                                            dataList[i].amount = usualData[i]
                                              .amount
                                              ? usualData[i].amount
                                              : "";
                                            dataList[i].tax = usualData[i].tax
                                              ? usualData[i].tax
                                              : "";
                                            dataList[i].totalAmount = usualData[
                                              i
                                            ].totalAmount
                                              ? usualData[i].totalAmount
                                              : "";
                                            purchaseOrderDetails[i].quantity =
                                              usualData[i].quantity
                                                ? usualData[i].quantity
                                                : "";
                                            purchaseOrderDetails[i].rate =
                                              usualData[i].rate
                                                ? usualData[i].rate
                                                : "";
                                            purchaseOrderDetails[i].taxPrice =
                                              usualData[i].taxPrice
                                                ? usualData[i].taxPrice
                                                : "";
                                            purchaseOrderDetails[i].price =
                                              usualData[i].price
                                                ? usualData[i].price
                                                : "";
                                            purchaseOrderDetails[i].amount =
                                              usualData[i].amount
                                                ? usualData[i].amount
                                                : "";
                                            purchaseOrderDetails[i].tax =
                                              usualData[i].tax
                                                ? usualData[i].tax
                                                : "";
                                            purchaseOrderDetails[
                                              i
                                            ].totalAmount = usualData[i]
                                              .totalAmount
                                              ? usualData[i].totalAmount
                                              : "";
                                          } else {
                                            purchaseOrderDetails[i].quantity =
                                              "";
                                            purchaseOrderDetails[i].rate = "";
                                            purchaseOrderDetails[i].taxPrice =
                                              "";
                                            purchaseOrderDetails[i].price = "";
                                            purchaseOrderDetails[i].amount = "";
                                            purchaseOrderDetails[i].tax = "";
                                            purchaseOrderDetails[
                                              i
                                            ].totalAmount = "";
                                          }
                                        }
                                        //排除空数组
                                        dataList = dataList.filter((item) =>
                                          item.hasOwnProperty("id")
                                        ); //dataList.push({},{},{},{},{},{},{},{},{},{});
                                        if (
                                          usualData.length - dataList.length >
                                          0
                                        ) {
                                          usualData.splice(
                                            dataList.length + 1,
                                            usualData.length - dataList.length
                                          );
                                          dataList.push({});
                                        } else {
                                          var addLength =
                                            dataList.length - usualData.length;
                                          for (var i = 0; i < addLength; i++) {
                                            usualData.push({});
                                          }
                                        }
                                        // 获取数据集合并传入采购订单中
                                        table.reload(
                                          "erpPurchaseOrder-add-table",
                                          {
                                            data: dataList,
                                            limit: dataList.length,
                                          }
                                        );
                                      }
                                    }
                                  );
                                  $("#erpInventoryList-btn-add").click(
                                    function () {
                                      admin.formOpen({
                                        area: "1200px",
                                        offset: "65px",
                                        title: "添加产品明细",
                                        path: "components/product/productDetailStorageForm.html",
                                      });
                                    }
                                  );
                                },
                              });
                              /*}else{
                                                    layer.msg("请选择是否过磅", {icon: 2, time: 1000});
                                                }*/
                            });
                          });
                        },
                      });
                    } else {
                      table.render({
                        elem: "#erpPurchaseOrder-add-table",
                        data: dataList,
                        limit: dataList.length,
                        cellMinWidth: 100,
                        cols: [
                          [
                            { type: "numbers", title: "序号", fixed: "left" },
                            {
                              field: "skuName",
                              align: "center",
                              title:
                                "物料名称<span style='color: red'>*</span>",
                              width: "150",
                            },
                            {
                              field: "skuCode",
                              align: "center",
                              title:
                                "物料编号<span style='color: red'>*</span>",
                              width: 140,
                            },
                            {
                              field: "skuSpec",
                              align: "center",
                              title: "规格型号",
                            },
                            {
                              field: "mainUnitName",
                              align: "center",
                              title: "采购单位",
                            },
                            {
                              field: "quantity",
                              align: "center",
                              title: "数量<span style='color: red'>*</span>",
                              width: 140,
                            },
                            {
                              field: "rate",
                              align: "center",
                              title: "税率(%)<span style='color: red'>*</span>",
                              width: 140,
                            },
                            {
                              field: "taxPrice",
                              align: "center",
                              title:
                                "含税单价<span style='color: red'>*</span>",
                              width: 140,
                            },
                            {
                              field: "price",
                              align: "center",
                              title: "单价<span style='color: red'>*</span>",
                            },
                            {
                              field: "amount",
                              align: "center",
                              title: "金额<span style='color: red'>*</span>",
                              templet: function (d) {
                                return (d.totalAmount - d.tax).toFixed(6);
                              },
                            },
                            {
                              field: "tax",
                              align: "center",
                              title: "税额<span style='color: red'>*</span>",
                            },
                            {
                              field: "totalAmount",
                              align: "center",
                              title:
                                "合计金额<span style='color:red;'>*</span>",
                            },
                            {
                              align: "center",
                              fixed: "right",
                              toolbar: "#erpPurchaseOrder-add-table-bar",
                              title: "操作",
                              width: 110,
                            },
                          ],
                        ],
                        done: function () {
                          layer.closeAll("loading");
                        },
                      });
                    }

                    // 工具条点击事件
                    table.on(
                      "tool(erpPurchaseOrder-add-table)",
                      function (obj) {
                        var data = obj.data;
                        var layEvent = obj.event;
                        if (obj.event === "del") {
                          //删除
                          doDelete(obj);
                        }
                      }
                    );

                    // 删除
                    var doDelete = function (obj) {
                      var index = $(obj.tr).data("index");
                      if (!$.isEmptyObject(obj.data)) {
                        layer.confirm(
                          "确定要删除吗？",
                          {
                            offset: "65px",
                            skin: "layui-layer-admin",
                          },
                          function (i) {
                            layer.close(i);
                            layer.load(2);
                            admin.req(
                              "enterprise/purchase/admin/purchaseOrderDetail/" +
                                obj.data.id,
                              {},
                              function (data) {
                                layer.closeAll("loading");
                                if (data.code == 200) {
                                  layer.msg(data.msg, { icon: 1, time: 500 });
                                  dataList.splice(index, 1);
                                  purchaseOrderDetails.splice(index, 1);
                                  usualData.splice(index, 1);
                                  if (codeArr.indexOf(obj.data.skuCode) >= 0) {
                                    codeArr.splice(
                                      codeArr.indexOf(obj.data.skuCode),
                                      1
                                    );
                                  }
                                  if ($.isEmptyObject(dataList[0])) {
                                    dataList = [];
                                    // 获取数据集合并传入请购单中
                                    table.reload("erpPurchaseOrder-add-table", {
                                      data: [{}],
                                      limit: 10,
                                    });
                                  } else {
                                    // 获取数据集合并传入请购单中
                                    table.reload("erpPurchaseOrder-add-table", {
                                      data: dataList,
                                      limit: dataList.length,
                                    });
                                  }
                                } else {
                                  layer.msg(data.msg, { icon: 2, time: 1000 });
                                }
                              },
                              "DELETE"
                            );
                          }
                        );
                      }
                    };
                  } else {
                    layer.msg("获取明细失败", { icon: 2, time: 1000 });
                  }
                },
                "GET"
              );

              form.val("erpPurchaseOrder-edit", data);

              // 表单提交事件
              form.on("submit(erpPurchaseOrder-edit-submit)", function (d) {
                if (purchaseOrderDetails.length > 0) {
                  purchaseOrderDetails = purchaseOrderDetails.filter(
                    (item) => item.skuCode !== undefined
                  );
                  d.field.purchaseOrderDetails = purchaseOrderDetails;
                  if (layEvent && layEvent == "audit") {
                    if (!$("input[name='status']:checked").val()) {
                      layer.msg("请审核", { icon: 5, time: 1000 });
                      return false;
                    }
                    var status = $("input[name='status']:checked").val();
                    if (status == "success") {
                      //通过
                      d.field.shippingStatus = "stayDelivery";
                    }
                  }
                  layer.load(2);
                  admin.req(
                    layEvent == "audit"
                      ? "enterprise/purchase/admin/purchaseOrder/audit"
                      : "enterprise/purchase/admin/purchaseOrder/update",
                    JSON.stringify(d.field),
                    function (res) {
                      layer.closeAll("loading");
                      if (res.code == 200) {
                        layer.msg(res.msg, { icon: 1, time: 500 });
                        table.reload("erpPurchaseOrder-table", {});
                        layer.closeAll("page");
                      } else {
                        layer.msg(res.msg, { icon: 2, time: 1000 });
                      }
                    },
                    layEvent == "audit" ? "POST" : "PUT",
                    false,
                    "application/json"
                  );
                } else {
                  layer.msg("未输入发生数据，无法保存", {
                    icon: 2,
                    time: 1000,
                  });
                }
                return false;
              });
            } else {
              var dataList = [];
              var purchaseOrderDetails = []; //明细数据
              var usualData = [{}];
              var codeArr = []; //物料选择集合

              //自定义验证规则
              form.verify({
                quantity: [
                  /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][0-9][1-9]|[1-9]\d{0,1})))|[ \t]*)$/,
                  "格式错误",
                ],
                rate: [
                  /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1})))|[ \t]*)$/,
                  "格式错误",
                ],
              });

              /*form.on("select(getIsWeigh)", function (data) {
                            dataList.splice(0, dataList.length);
                            usualData.splice(0, usualData.length);
                            dataList = [];
                            usualData = [];
                            purchaseOrderDetails = [];
                            codeArr = [];
                            // 获取数据集合并传入采购订单中
                            table.reload('erpPurchaseOrder-add-table', {
                                data: [{}],
                                limit: 10
                            });
                        })*/

              // 渲染表格
              table.render({
                elem: "#erpPurchaseOrder-add-table",
                data: dataList.length > 10 ? dataList : [{}],
                limit: dataList.length > 10 ? dataList.length : 10,
                cellMinWidth: 100,
                cols: [
                  [
                    { type: "numbers", title: "序号" },
                    {
                      field: "skuName",
                      align: "center",
                      title: "物料名称<span style='color: red'>*</span>",
                      templet:
                        '<div><span class="erpInventoryId" style="display: block;cursor: pointer;" data-add="{{d.skuName != null ? false : true}}">{{d.skuName != null ? d.skuName : "请选择物料"}}</span></div>',
                      width: "150",
                    },
                    {
                      field: "skuCode",
                      align: "center",
                      title: "物料编号<span style='color: red'>*</span>",
                      width: 140,
                    },
                    { field: "skuSpec", align: "center", title: "规格型号" },
                    {
                      field: "mainUnitName",
                      align: "center",
                      title: "采购单位",
                    },
                    {
                      field: "quantity",
                      align: "center",
                      title: "数量<span style='color: red'>*</span>",
                      templet: "#quantity",
                      width: 140,
                    },
                    {
                      field: "rate",
                      align: "center",
                      title: "税率(%)<span style='color: red'>*</span>",
                      templet: "#rate",
                      width: 140,
                    },
                    {
                      field: "taxPrice",
                      align: "center",
                      title: "含税单价<span style='color: red'>*</span>",
                      templet: "#taxPrice",
                      width: 140,
                    },
                    {
                      field: "price",
                      align: "center",
                      title: "单价<span style='color: red'>*</span>",
                    },
                    {
                      field: "amount",
                      align: "center",
                      title: "金额<span style='color: red'>*</span>",
                    },
                    {
                      field: "tax",
                      align: "center",
                      title: "税额<span style='color: red'>*</span>",
                    },
                    {
                      field: "totalAmount",
                      align: "center",
                      title: "合计金额",
                    },
                    {
                      align: "center",
                      toolbar: "#erpPurchaseOrder-add-table-bar",
                      title: "操作",
                    },
                  ],
                ],
                done: function () {
                  $("input[name='quantity']").on("input", function (e) {
                    //获取input输入的值
                    var curValue = e.delegateTarget.value;
                    var curIndex = $(this).closest("tr").data("index");
                    if (purchaseOrderDetails[curIndex]) {
                      purchaseOrderDetails[curIndex].quantity = curValue;
                    }
                    dataList[curIndex].quantity = curValue;
                    usualData[curIndex].quantity = curValue;
                    if (usualData.length - curIndex - 1 < 10) {
                      var addLength = 10 - (usualData.length - curIndex - 1);
                      for (var i = 0; i < addLength; i++) {
                        usualData.push({});
                      }
                    }
                    var rate = "";
                    var taxPrice = "";
                    $(this)
                      .closest("tr")
                      .find("td")
                      .each(function () {
                        if ($(this).data("field") == "rate") {
                          rate = $(this).find("input").val();
                        }
                        if ($(this).data("field") == "taxPrice") {
                          taxPrice = $(this).find("input").val();
                        }
                      });
                    //计算价格
                    calculatePrice(curValue, rate, taxPrice, $(this), curIndex);
                  });
                  $("input[name='rate']").on("input", function (e) {
                    //获取input输入的值
                    var curValue = e.delegateTarget.value;
                    var curIndex = $(this).closest("tr").data("index");
                    if (purchaseOrderDetails[curIndex]) {
                      purchaseOrderDetails[curIndex].rate = curValue;
                    }
                    dataList[curIndex].rate = curValue;
                    usualData[curIndex].rate = curValue;
                    if (usualData.length - curIndex - 1 < 10) {
                      var addLength = 10 - (usualData.length - curIndex - 1);
                      for (var i = 0; i < addLength; i++) {
                        usualData.push({});
                      }
                    }
                    var quantity = "";
                    var taxPrice = "";
                    $(this)
                      .closest("tr")
                      .find("td")
                      .each(function () {
                        if ($(this).data("field") == "quantity") {
                          quantity = $(this).find("input").val();
                        }
                        if ($(this).data("field") == "taxPrice") {
                          taxPrice = $(this).find("input").val();
                        }
                      });
                    //计算价格
                    calculatePrice(
                      quantity,
                      curValue,
                      taxPrice,
                      $(this),
                      curIndex
                    );
                  });
                  $("input[name='taxPrice']").on("input", function (e) {
                    //获取input输入的值
                    var curValue = e.delegateTarget.value;
                    var curIndex = $(this).closest("tr").data("index");
                    if (purchaseOrderDetails[curIndex]) {
                      purchaseOrderDetails[curIndex].taxPrice = curValue;
                    }
                    dataList[curIndex].taxPrice = curValue;
                    usualData[curIndex].taxPrice = curValue;
                    if (usualData.length - curIndex - 1 < 10) {
                      var addLength = 10 - (usualData.length - curIndex - 1);
                      for (var i = 0; i < addLength; i++) {
                        usualData.push({});
                      }
                    }
                    var quantity = "";
                    var rate = "";
                    $(this)
                      .closest("tr")
                      .find("td")
                      .each(function () {
                        if ($(this).data("field") == "quantity") {
                          quantity = $(this).find("input").val();
                        }
                        if ($(this).data("field") == "rate") {
                          rate = $(this).find("input").val();
                        }
                      });
                    //计算价格
                    calculatePrice(quantity, rate, curValue, $(this), curIndex);
                  });

                  //通过数量、税率、含税单价计算价格
                  function calculatePrice(
                    quantity,
                    rate,
                    taxPrice,
                    $cur,
                    curIndex
                  ) {
                    //计算单价
                    if (rate != "" && taxPrice != "") {
                      var price = (taxPrice * 100) / (Number(rate) + 100);
                      $cur
                        .closest("tr")
                        .find("td")
                        .each(function () {
                          if ($(this).data("field") == "price") {
                            $(this).find("div").text(price.toFixed(2));
                            dataList[curIndex].price = price.toFixed(2);
                            usualData[curIndex].price = price.toFixed(2);
                            if (purchaseOrderDetails[curIndex]) {
                              purchaseOrderDetails[curIndex].price =
                                price.toFixed(2);
                            }
                          }
                        });
                    } else {
                      $cur
                        .closest("tr")
                        .find("td")
                        .each(function () {
                          if ($(this).data("field") == "price") {
                            $(this).find("div").text("");
                            dataList[curIndex].price = "";
                            usualData[curIndex].price = "";
                            if (purchaseOrderDetails[curIndex]) {
                              purchaseOrderDetails[curIndex].price = "";
                            }
                          }
                        });
                    }
                    //计算金额
                    if (quantity != "" && rate != "" && taxPrice != "") {
                      var amount =
                        (quantity * taxPrice * 100) / (Number(rate) + 100);
                      $cur
                        .closest("tr")
                        .find("td")
                        .each(function () {
                          if ($(this).data("field") == "amount") {
                            $(this).find("div").text(amount.toFixed(2));
                            dataList[curIndex].amount = amount.toFixed(2);
                            usualData[curIndex].amount = amount.toFixed(2);
                            if (purchaseOrderDetails[curIndex]) {
                              purchaseOrderDetails[curIndex].amount =
                                amount.toFixed(2);
                            }
                          }
                        });
                    } else {
                      $cur
                        .closest("tr")
                        .find("td")
                        .each(function () {
                          if ($(this).data("field") == "amount") {
                            $(this).find("div").text("");
                            dataList[curIndex].amount = "";
                            usualData[curIndex].amount = "";
                            if (purchaseOrderDetails[curIndex]) {
                              purchaseOrderDetails[curIndex].amount = "";
                            }
                          }
                        });
                    }
                    //计算税额
                    if (quantity != "" && rate != "" && taxPrice != "") {
                      var tax =
                        quantity * taxPrice -
                        (quantity * taxPrice * 100) / (Number(rate) + 100);
                      $cur
                        .closest("tr")
                        .find("td")
                        .each(function () {
                          if ($(this).data("field") == "tax") {
                            $(this).find("div").text(tax.toFixed(2));
                            dataList[curIndex].tax = tax.toFixed(2);
                            usualData[curIndex].tax = tax.toFixed(2);
                            if (purchaseOrderDetails[curIndex]) {
                              purchaseOrderDetails[curIndex].tax =
                                tax.toFixed(2);
                            }
                          }
                        });
                    } else {
                      $cur
                        .closest("tr")
                        .find("td")
                        .each(function () {
                          if ($(this).data("field") == "tax") {
                            $(this).find("div").text("");
                            dataList[curIndex].tax = "";
                            usualData[curIndex].tax = "";
                            if (purchaseOrderDetails[curIndex]) {
                              purchaseOrderDetails[curIndex].tax = "";
                            }
                          }
                        });
                    }
                    //计算合计金额
                    if (quantity != "" && taxPrice != "") {
                      var totalAmount = quantity * taxPrice;
                      $cur
                        .closest("tr")
                        .find("td")
                        .each(function () {
                          if ($(this).data("field") == "totalAmount") {
                            $(this).find("div").text(totalAmount.toFixed(2));
                            dataList[curIndex].totalAmount =
                              totalAmount.toFixed(2);
                            usualData[curIndex].totalAmount =
                              totalAmount.toFixed(2);
                            if (purchaseOrderDetails[curIndex]) {
                              purchaseOrderDetails[curIndex].totalAmount =
                                totalAmount.toFixed(2);
                            }
                          }
                        });
                    } else {
                      $cur
                        .closest("tr")
                        .find("td")
                        .each(function () {
                          if ($(this).data("field") == "totalAmount") {
                            $(this).find("div").text("");
                            dataList[curIndex].totalAmount = "";
                            usualData[curIndex].totalAmount = "";
                            if (purchaseOrderDetails[curIndex]) {
                              purchaseOrderDetails[curIndex].totalAmount = "";
                            }
                          }
                        });
                    }
                  }

                  layer.closeAll("loading");
                  $(".erpInventoryId").each(function (index) {
                    $(this).click(function () {
                      let list = purchaseOrderDetails;
                      let skuCodes = list
                        .filter((item) => item.skuCode !== undefined)
                        .map((item) => item.skuCode);
                      let infos = skuCodes.join(",");
                      /*var isWeigh = $("select[name='isWeigh']").val();
                                        if(isWeigh != ""){*/
                      var isAdd = $(this).data("add");
                      //获取物料数据
                      var erpInventoryList = admin.open({
                        type: 1,
                        title: "物料列表",
                        area: ["1300px", "750px"],
                        offset: ["130px", "350px"],
                        content: $("#erpInventoryList").html(),
                        success: function () {
                          form.render("select");

                          admin.initDataSelectTree(
                            true,
                            "enterprise/product/admin/productType/getTreeData",
                            null,
                            "addSelfCollectedGoodsProductCategoryId",
                            null,
                            "物料类别"
                          );

                          var codes = "";
                          for (var i = 0; i < codeArr.length; i++) {
                            if (i == 0) {
                              codes = '"' + codeArr[i] + '"';
                            } else {
                              codes += "," + '"' + codeArr[i] + '"';
                            }
                          }

                          // 渲染表格
                          table.render({
                            elem: "#erpInventoryList-table",
                            url:
                              config.base +
                              "enterprise/product/admin/productDetail/list",
                            method: "GET",
                            where: {
                              codes: infos,
                            },
                            page: true,
                            cols: [
                              [
                                { type: "checkbox" },
                                {
                                  field: "skuCode",
                                  align: "center",
                                  title: "物料编号",
                                },
                                {
                                  field: "skuName",
                                  align: "center",
                                  title: "物料名称",
                                },
                                {
                                  field: "skuSpec",
                                  align: "center",
                                  title: "规格型号",
                                },
                                {
                                  field: "productTypeName",
                                  align: "center",
                                  title: "物料类别",
                                },
                                {
                                  field: "mainUnitName",
                                  align: "center",
                                  title: "主计量单位",
                                },
                                {
                                  field: "mainUnitRate",
                                  align: "center",
                                  style: innerWidth,
                                  title: "主计量单位换算率",
                                },
                                {
                                  field: "subUnitName",
                                  align: "center",
                                  title: "辅计量单位",
                                },
                                {
                                  field: "subUnitRate",
                                  align: "center",
                                  style: innerWidth,
                                  title: "辅计量单位换算率",
                                },
                              ],
                            ],
                          });

                          // 搜索按钮点击事件
                          $("#erpInventoryList-btn-search").click(function () {
                            var name = $("#erpInventoryList-name").val();
                            var code = $("#erpInventoryList-code").val();
                            var skuSpec = $("#erpInventoryList-spec").val();
                            var way = $("#erpInventoryList-way").val();
                            var categoryId = $(
                              "input[name=addSelfCollectedGoodsProductCategoryId]"
                            ).val();
                            table.reload("erpInventoryList-table", {
                              page: { curr: 1 },
                              where: {
                                skuCode: code,
                                skuName: name,
                                skuSpec: skuSpec,
                                pricingMethod: way,
                                categoryId: categoryId,
                              },
                            });
                          });

                          // 确认选择
                          $("#erpInventoryList-btn-choose").click(function () {
                            //hezhou
                            var checkStatus = table.checkStatus(
                              "erpInventoryList-table"
                            ); //test即为基础参数id对应的值
                            var dataS = checkStatus.data;
                            for (var i = 0; i < dataS.length; i++) {
                              dataS[i].productName = dataS[i].skuName;
                              dataS[i].skuSpec = dataS[i].skuSpec;
                            }

                            if (checkStatus.data.length == 0) {
                              layer.msg("请选择物料", { icon: 2, time: 1000 });
                            } else {
                              layer.close(erpInventoryList);
                              if (dataList.length >= 10) {
                                dataList.splice(dataList.length - 10, 10);
                              }
                              if (!isAdd) {
                                dataList.splice(index, 1);
                                usualData.splice(index, 1);
                                codeArr.splice(index, 1);
                                for (var i = 0; i < dataS.length; i++) {
                                  dataList.splice(index + i, 0, dataS[i]);
                                  usualData.splice(index + i, 0, {});
                                  codeArr.splice(
                                    index + i,
                                    0,
                                    dataS[i].skuCode
                                  );
                                }
                              } else {
                                for (var i = 0; i < dataS.length; i++) {
                                  dataList.push(dataS[i]);
                                  usualData.push({});
                                  codeArr.push(dataS[i].skuCode);
                                }
                              }

                              //处理数据并存储
                              for (var i = 0; i < dataList.length; i++) {
                                if (!purchaseOrderDetails[i]) {
                                  purchaseOrderDetails.push({});
                                }
                                purchaseOrderDetails[i].skuCode =
                                  dataList[i].skuCode;
                                purchaseOrderDetails[i].skuName =
                                  dataList[i].skuName;
                                purchaseOrderDetails[i].unitName =
                                  dataList[i].mainUnitName;
                                purchaseOrderDetails[i].skuSpec =
                                  dataList[i].skuSpec;
                                purchaseOrderDetails[i].pricingMethodName =
                                  dataList[i].pricingMethodName;
                                purchaseOrderDetails[i].productTypeName =
                                  dataList[i].productTypeName;
                                purchaseOrderDetails[i].mainUnitRate =
                                  dataList[i].mainUnitRate;
                                purchaseOrderDetails[i].subUnitName =
                                  dataList[i].subUnitName;
                                purchaseOrderDetails[i].subUnitRate =
                                  dataList[i].subUnitRate;
                                purchaseOrderDetails[i].productName =
                                  dataList[i].skuName;
                                purchaseOrderDetails[i].specifications =
                                  dataList[i].skuSpec;
                                if (usualData[i].id) {
                                  dataList[i].quantity = usualData[i].quantity
                                    ? usualData[i].quantity
                                    : "";
                                  dataList[i].rate = usualData[i].rate
                                    ? usualData[i].rate
                                    : "";
                                  dataList[i].taxPrice = usualData[i].taxPrice
                                    ? usualData[i].taxPrice
                                    : "";
                                  dataList[i].price = usualData[i].price
                                    ? usualData[i].price
                                    : "";
                                  dataList[i].amount = usualData[i].amount
                                    ? usualData[i].amount
                                    : "";
                                  dataList[i].tax = usualData[i].tax
                                    ? usualData[i].tax
                                    : "";
                                  dataList[i].totalAmount = usualData[i]
                                    .totalAmount
                                    ? usualData[i].totalAmount
                                    : "";
                                  purchaseOrderDetails[i].quantity = usualData[
                                    i
                                  ].quantity
                                    ? usualData[i].quantity
                                    : "";
                                  purchaseOrderDetails[i].rate = usualData[i]
                                    .rate
                                    ? usualData[i].rate
                                    : "";
                                  purchaseOrderDetails[i].taxPrice = usualData[
                                    i
                                  ].taxPrice
                                    ? usualData[i].taxPrice
                                    : "";
                                  purchaseOrderDetails[i].price = usualData[i]
                                    .price
                                    ? usualData[i].price
                                    : "";
                                  purchaseOrderDetails[i].amount = usualData[i]
                                    .amount
                                    ? usualData[i].amount
                                    : "";
                                  purchaseOrderDetails[i].tax = usualData[i].tax
                                    ? usualData[i].tax
                                    : "";
                                  purchaseOrderDetails[i].totalAmount =
                                    usualData[i].totalAmount
                                      ? usualData[i].totalAmount
                                      : "";
                                } else {
                                  purchaseOrderDetails[i].quantity = "";
                                  purchaseOrderDetails[i].rate = "";
                                  purchaseOrderDetails[i].taxPrice = "";
                                  purchaseOrderDetails[i].price = "";
                                  purchaseOrderDetails[i].amount = "";
                                  purchaseOrderDetails[i].tax = "";
                                  purchaseOrderDetails[i].totalAmount = "";
                                }
                              }
                              //排除空数组
                              dataList = dataList.filter((item) =>
                                item.hasOwnProperty("id")
                              ); //dataList.push({},{},{},{},{},{},{},{},{},{});
                              if (usualData.length - dataList.length > 0) {
                                usualData.splice(
                                  dataList.length + 1,
                                  usualData.length - dataList.length
                                );
                                dataList.push({});
                              } else {
                                var addLength =
                                  dataList.length - usualData.length;
                                for (var i = 0; i < addLength; i++) {
                                  usualData.push({});
                                }
                              }
                              console.log(
                                table.cache["erpPurchaseOrder-add-table"]
                              );
                              // 获取数据集合并传入采购订单中
                              table.reload("erpPurchaseOrder-add-table", {
                                data: dataList,
                                limit: dataList.length,
                              });
                            }
                          });
                          $("#erpInventoryList-btn-add").click(function () {
                            admin.formOpen({
                              area: "1200px",
                              offset: "65px",
                              title: "添加产品明细",
                              path: "components/product/productDetailStorageForm.html",
                            });
                          });
                        },
                      });
                      /*}else{
                                            layer.msg("请选择是否过磅", {icon: 2, time: 1000});
                                        }*/
                    });
                  });
                },
              });

              // 工具条点击事件
              table.on("tool(erpPurchaseOrder-add-table)", function (obj) {
                var data = obj.data;
                var layEvent = obj.event;
                if (obj.event === "del") {
                  //删除
                  doDelete(obj);
                }
              });

              // 删除
              var doDelete = function (obj) {
                var index = $(obj.tr).data("index");
                if (!$.isEmptyObject(obj.data)) {
                  layer.confirm(
                    "确定要删除吗？",
                    {
                      offset: "65px",
                      skin: "layui-layer-admin",
                    },
                    function (i) {
                      layer.close(i);
                      dataList.splice(index, 1);
                      purchaseOrderDetails.splice(index, 1);
                      usualData.splice(index, 1);
                      if (codeArr.indexOf(obj.data.skuCode) >= 0) {
                        codeArr.splice(codeArr.indexOf(obj.data.skuCode), 1);
                      }
                      if ($.isEmptyObject(dataList[0])) {
                        dataList = [];
                        // 获取数据集合并传入请购单中
                        table.reload("erpPurchaseOrder-add-table", {
                          data: [{}],
                          limit: 10,
                        });
                      } else {
                        // 获取数据集合并传入请购单中
                        table.reload("erpPurchaseOrder-add-table", {
                          data: dataList,
                          limit: dataList.length,
                        });
                      }
                    }
                  );
                }
              };

              // 表单提交事件
              form.on("submit(erpPurchaseOrder-form-submit)", function (data) {
                if (purchaseOrderDetails.length > 0) {
                  var field = data.field;
                  if (purchaseOrderDetails) {
                    purchaseOrderDetails = purchaseOrderDetails.filter(
                      (item) =>
                        item.skuCode !== undefined && item.skuCode !== null
                    );
                  }
                  field.purchaseOrderDetails = purchaseOrderDetails;
                  //dataList.push({},{},{},{},{},{},{},{},{},{});
                  layer.load(2);
                  console.log("field", field);
                  // admin.req('enterprise/purchase/admin/purchaseOrder/add', JSON.stringify(field), function (data) {
                  //     layer.closeAll('loading');
                  //     if (data.code == 200) {
                  //         layer.msg(data.msg, {icon: 1, time: 500});
                  //         table.reload('erpPurchaseOrder-table', {});
                  //         layer.closeAll('page');
                  //     } else {
                  //         layer.msg(data.msg, {icon: 2, time: 1000});
                  //     }
                  // }, 'POST', false, "application/json");
                } else {
                  layer.msg("未输入发生数据，无法保存", {
                    icon: 2,
                    time: 1000,
                  });
                }
                return false;
              });
            }
          },
        });
      };

      // 删除
      var doDelete = function (obj) {
        layer.confirm(
          "确定要删除吗？",
          {
            offset: "65px",
            skin: "layui-layer-admin",
          },
          function (i) {
            layer.close(i);
            layer.load(2);
            admin.req(
              "enterprise/purchase/admin/purchaseOrder/" + obj.data.id,
              {},
              function (data) {
                layer.closeAll("loading");
                if (data.code == 200) {
                  layer.msg(data.msg, { icon: 1, time: 500 });
                  obj.del();
                } else {
                  layer.msg(data.msg, { icon: 2, time: 1000 });
                }
              },
              "DELETE"
            );
          }
        );
      };

      // 生成入库单
      var generate = function (data) {
        /*admin.putTempData('t_erp_purchase_order', data);
            admin.popupCenter({
                title: "新增入库单信息",
                area: ['1200px','800px'],
                path: 'pages/procurement/purchaseReceipt/add.html?type=purchaseOrder',
                finish: function () {
                    table.reload('erpPurchaseOrder-table', {});
                }
            });*/
      };

      // 关闭
      var doClose = function (obj) {
        layer.confirm(
          "确定要关闭吗？",
          {
            offset: "65px",
            skin: "layui-layer-admin",
          },
          function (i) {
            layer.close(i);
            layer.load(2);
            admin.req(
              "enterprise/purchase/admin/purchaseOrder/close",
              { id: obj.data.id },
              function (data) {
                layer.closeAll("loading");
                if (data.code == 200) {
                  layer.msg(data.msg, { icon: 1, time: 500 });
                  table.reload("erpPurchaseOrder-table", {});
                } else {
                  layer.msg(data.msg, { icon: 2, time: 1000 });
                }
              },
              "GET"
            );
          }
        );
      };

      //详情
      var showViewModel = function (data) {
        admin.open({
          type: 1,
          area: ["1200px", "800px"],
          title: "采购订单详情",
          content: $("#erpPurchaseOrder-view").html(),
          success: function () {
            form.val("erpPurchaseOrder-view", data);
            var dataList = [];
            var status = data.status;
            if (status == "success" || status == "fail") {
              $("#audit").show();
              $("input[name='status']").each(function () {
                if ($(this).val() == status) {
                  $(this).attr("checked", true);
                }
              });
              if (status == "fail") {
                $("#reason").show();
              }
            }
            // 获取供应商
            admin.initDataSelect(
              "enterprise/purchase/admin/supplierInfoPass/list",
              { limit: 99999 },
              "supplierId",
              data.supplierId,
              "供应商",
              "corporateName",
              null
            );

            // 获取部门
            admin.initDataSelectTree(
              true,
              "user/admin/role/getTreeData",
              null,
              "selectDepartmentView",
              data.departmentId,
              "部门",
              null
            );

            // 获取申请人
            admin.initDataSelect(
              "user/admin/user/list",
              {
                limit: 9999,
                departmentId: data.departmentId,
              },
              "personnelId",
              data.personnelId,
              "申请人",
              "nickname",
              null
            );

            //获取明细数据
            admin.req(
              "enterprise/purchase/admin/purchaseOrderDetail/list",
              { purchaseOrderId: data.id },
              function (data) {
                if (200 == data.code) {
                  var detail = data.data;
                  for (var i = 0; i < detail.length; i++) {
                    dataList.push({});
                    dataList[i].skuCode = detail[i].skuCode;
                    dataList[i].skuName = detail[i].productName;
                    dataList[i].mainUnitName = detail[i].unitName;
                    dataList[i].skuSpec = detail[i].specifications
                      ? detail[i].specifications
                      : "";
                    dataList[i].quantity = detail[i].quantity
                      ? detail[i].quantity
                      : "";
                    dataList[i].rate = detail[i].rate ? detail[i].rate : "";
                    dataList[i].taxPrice = detail[i].taxPrice
                      ? detail[i].taxPrice
                      : "";
                    dataList[i].price = detail[i].price ? detail[i].price : "";
                    dataList[i].amount = detail[i].amount
                      ? detail[i].amount
                      : "";
                    dataList[i].tax = detail[i].tax ? detail[i].tax : "";
                    dataList[i].totalAmount = detail[i].totalAmount
                      ? detail[i].totalAmount
                      : "";
                  }
                  // 渲染表格
                  table.render({
                    elem: "#erpPurchaseOrder-add-table",
                    data: dataList,
                    limit: dataList.length,
                    cellMinWidth: 100,
                    cols: [
                      [
                        { type: "numbers", title: "序号" },
                        {
                          field: "skuName",
                          align: "center",
                          title: "物料名称<span style='color: red'>*</span>",
                          templet:
                            '<div><span class="erpInventoryId" style="display: block;cursor: pointer;" data-add="{{d.skuName != null ? false : true}}">{{d.skuName != null ? d.skuName : "请选择物料"}}</span></div>',
                          width: "150",
                        },
                        {
                          field: "skuCode",
                          align: "center",
                          title: "物料编号<span style='color: red'>*</span>",
                          width: 140,
                        },
                        {
                          field: "skuSpec",
                          align: "center",
                          title: "规格型号",
                        },
                        {
                          field: "mainUnitName",
                          align: "center",
                          title: "采购单位",
                        },
                        {
                          field: "quantity",
                          align: "center",
                          title: "数量<span style='color: red'>*</span>",
                          templet: "#quantity",
                          width: 140,
                        },
                        {
                          field: "rate",
                          align: "center",
                          title: "税率(%)<span style='color: red'>*</span>",
                          templet: "#rate",
                          width: 140,
                        },
                        {
                          field: "taxPrice",
                          align: "center",
                          title: "含税单价<span style='color: red'>*</span>",
                          templet: "#taxPrice",
                          width: 140,
                        },
                        {
                          field: "price",
                          align: "center",
                          title: "单价<span style='color: red'>*</span>",
                        },
                        {
                          field: "amount",
                          align: "center",
                          title: "金额<span style='color: red'>*</span>",
                          templet: function (d) {
                            return (d.totalAmount - d.tax).toFixed(6);
                          },
                        },
                        {
                          field: "tax",
                          align: "center",
                          title: "税额<span style='color: red'>*</span>",
                        },
                        {
                          field: "totalAmount",
                          align: "center",
                          title: "合计金额<span style='color:red;'>*</span>",
                        },
                      ],
                    ],
                    done: function () {
                      layer.closeAll("loading");
                    },
                  });
                } else {
                  layer.msg("获取明细失败", { icon: 2, time: 1000 });
                }
              },
              "GET"
            );
          },
        });
      };

      //物流
      var logistics = function (data) {
        admin.open({
          type: 1,
          area: ["80%", "700px"],
          title: "物流信息",
          content: $("#logisticsList").html(),
          success: function () {
            // 获取供应商
            admin.req(
              "enterprise/purchase/admin/supplierInfoPass/list",
              { limit: 99999 },
              function (data) {
                if (200 == data.code) {
                  laytpl(erpLogistics1SupplierId_list.innerHTML).render(
                    data.data,
                    function (html) {
                      $("#erpLogistics1-supplierId").html(html);
                      form.render("select");
                    }
                  );
                } else {
                  layer.msg("获取供应商失败", { icon: 2, time: 1000 });
                }
              },
              "GET"
            );

            // 渲染表格
            table.render({
              elem: "#erpLogistics1-table",
              url: config.base + "api-erp/erpLogistics/list",
              method: "GET",
              where: {
                access_token: config.getToken().access_token,
                sn: data.sn,
              },
              page: true,
              cols: [
                [
                  { type: "numbers" },
                  {
                    field: "transportOrderNo",
                    align: "center",
                    title: "物流单号",
                    width: 180,
                  },
                  {
                    field: "sn",
                    align: "center",
                    title: "所属采购单",
                    width: 180,
                  },
                  {
                    field: "transCompanyName",
                    align: "center",
                    title: "所属物流公司",
                  },
                  { field: "carNumber", align: "center", title: "车牌号" },
                  { field: "driverName", align: "center", title: "司机" },
                  {
                    field: "corporateName",
                    align: "center",
                    title: "发货供应商",
                  },
                  { field: "statusName", align: "center", title: "状态" },
                  {
                    field: "createTime",
                    align: "center",
                    title: "创建时间",
                    width: 180,
                  },
                  {
                    align: "center",
                    toolbar: "#erpLogistics1-table-bar",
                    title: "操作",
                    width: 200,
                  },
                ],
              ],
            });

            // 添加按钮点击事件
            $("#erpLogistics1-btn-add").click(function () {
              showEditModel();
            });

            // 工具条点击事件
            table.on("tool(erpLogistics1-table)", function (obj) {
              var data = obj.data;
              var layEvent = obj.event;
              if (obj.event === "view") {
                //详情
                showViewModel(data);
              } else if (obj.event === "progress") {
                //物流进度
                progress(data);
              } else if (obj.event === "view1") {
                //不需要过磅的详情
                showViewModel(data, layEvent);
              } else if (obj.event === "info") {
                //物流信息
                info(data);
              } else if (obj.event === "complete") {
                //完成车辆计划
                completePlan(data);
              }
            });

            //详情
            var showViewModel = function (data, type) {
              layer.load(2);
              var content = $("#logistics-view").html();
              if (type == "view1") {
                content = $("#logistics-view1").html();
              }
              var logisticsView = layer.open({
                type: 1,
                title: "物流详情",
                area: ["80%", "80%"],
                offset: ["200px", "280px"],
                content: content,
                success: function () {
                  // 查询供应商信息
                  admin.req(
                    "api-erp/supplier/detail",
                    { id: data.supplierId },
                    function (data) {
                      layer.closeAll("loading");
                      if (data.code == 200) {
                        laytpl(supplier_info.innerHTML).render(
                          data.data,
                          function (html) {
                            $("#supplierInfo").html(html);
                            form.render("select");
                          }
                        );
                      } else {
                        layer.msg(data.msg, { icon: 2, time: 1000 });
                      }
                    },
                    "GET"
                  );

                  if (type != "view1") {
                    // 二维码生成
                    var qrcode = new QRCode(document.getElementById("qrcode"), {
                      width: 150,
                      height: 150,
                    });
                    // 通过物流ID获取车辆计划号
                    admin.req(
                      "api-erp/erpDeliveryRecord/getErpDeliveryRecord",
                      { erpLogisticsId: data.id },
                      function (data) {
                        layer.closeAll("loading");
                        if (data.code == 200) {
                          var record = data.data[0];

                          function makeCode() {
                            var card = '{"1":"' + record.weighOrderCarNo + '"}';
                            var encodedData = window.btoa(card); // 编码
                            qrcode.makeCode(encodedData);
                          }

                          makeCode();
                        } else {
                          layer.msg(data.msg, { icon: 2, time: 1000 });
                        }
                      },
                      "GET",
                      true
                    );

                    if (null != data) {
                      laytpl(car_info.innerHTML).render(data, function (html) {
                        $("#carInfo").html(html);
                        form.render("select");
                      });
                      laytpl(driver_info.innerHTML).render(
                        data,
                        function (html) {
                          $("#driverInfo").html(html);
                          form.render("select");
                        }
                      );
                    }
                  }

                  //查询运输的物料信息 -- 发货记录
                  // 渲染表格
                  table.render({
                    elem: "#deliveryRecord-table",
                    url: config.base + "api-erp/erpDeliveryRecord/list",
                    method: "GET",
                    where: {
                      access_token: config.getToken().access_token,
                      erpLogisticsId: data.id,
                    },
                    page: true,
                    cols: [
                      [
                        { type: "numbers" },
                        {
                          field: "inventoryCode",
                          align: "center",
                          title: "物料编号",
                        },
                        {
                          field: "inventoryName",
                          align: "center",
                          title: "物料名称",
                        },
                        {
                          field: "inventorySpec",
                          align: "center",
                          title: "规格型号",
                        },
                        {
                          field: "mainUnitName",
                          align: "center",
                          title: "单位",
                        },
                        {
                          field: "productTypeName",
                          align: "center",
                          title: "物料类别",
                        },
                        {
                          field: "deliveryQuantity",
                          align: "center",
                          title: "发货数量",
                        },
                      ],
                    ],
                  });
                },
              });
            };

            //物流进度
            var progress = function (data) {
              layer.load(2);
              var logisticsView = layer.open({
                type: 1,
                title: "物流进度",
                area: ["70%", "700px"],
                offset: ["200px", "280px"],
                content: $("#logistics-progress").html(),
                success: function () {
                  // 查询物流进度
                  admin.req(
                    "api-erp/erpLogisticsProgress/getErpLogisticsProgress",
                    { erpLogisticsId: data.id },
                    function (data) {
                      layer.closeAll("loading");
                      if (data.code == 200) {
                        laytpl(logistics_progress.innerHTML).render(
                          data.data,
                          function (html) {
                            $("#logisticsProgress").html(html);
                            form.render("select");
                          }
                        );
                      } else {
                        layer.msg(data.msg, { icon: 2, time: 1000 });
                      }
                    },
                    "GET",
                    true
                  );
                },
              });
            };

            //物流信息
            var info = function (data) {
              var logisticsInfo = layer.open({
                type: 1,
                title: "物流信息",
                area: "800px",
                offset: ["200px", "280px"],
                content: $("#logistics-info").html(),
                success: function () {
                  // 物流公司
                  $("#company").val(data.logisticsCompany);
                  $("#sn").val(data.transportOrderNo);
                },
              });
            };

            // 完成车辆计划
            var completePlan = function (data) {
              layer.confirm(
                "确定要完成车辆计划吗？",
                {
                  offset: "65px",
                  skin: "layui-layer-admin",
                },
                function (i) {
                  layer.close(i);
                  layer.load(2);
                  admin.req(
                    "api-erp/erpLogistics/completePlan",
                    { id: data.id },
                    function (data) {
                      layer.closeAll("loading");
                      if (data.code == 200) {
                        layer.msg(data.msg, { icon: 1, time: 500 });
                        table.reload("erpLogistics-table");
                      } else {
                        layer.msg(data.msg, { icon: 2, time: 1000 });
                      }
                    },
                    "GET"
                  );
                }
              );
            };

            // 搜索按钮点击事件
            $("#erpLogistics1-btn-search").click(function () {
              var transportOrderNo = $("#erpLogistics1-transportOrderNo").val();
              var supplierId = $("#erpLogistics1-supplierId").val();
              var status = $("#erpLogistics1-status").val();
              table.reload("erpLogistics1-table", {
                page: { curr: 1 },
                where: {
                  transportOrderNo: transportOrderNo,
                  supplierId: supplierId,
                  status: status,
                },
              });
            });
          },
        });
      };

      // 搜索
      form.on("submit(formSubSearchLog)", function (data) {
        insTb.reload({ where: data.field, page: { curr: 1 } }, "data");
      });

      // 重置搜索
      form.on("submit(resets)", function (data) {
        console.log(12333);
        insTb.reload(
          { where: admin.resetSearch(data.field), page: { curr: 1 } },
          "data"
        );
      });

      // 导出excel
      $("#purchaseOrderBtnExport").click(function () {
        var checkRows = table.checkStatus("erpPurchaseOrder-table");
        if (checkRows.data.length == 0) {
          layer.msg("请选择要导出的数据", { icon: 2 });
        } else {
          table.exportFile(insTb.config.id, checkRows.data, "xls");
        }
      });
    }
  );
</script>
